babylon.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. /** @hidden */
  441. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  442. // Rebuild shaders source code
  443. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  444. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  445. vertexCode = prefix + vertexCode;
  446. fragmentCode = prefix + fragmentCode;
  447. // Number lines of shaders source code
  448. var i = 2;
  449. var regex = /\n/gm;
  450. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  451. i = 2;
  452. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  453. // Dump shaders name and formatted source code
  454. if (this.name.vertexElement) {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  457. }
  458. else if (this.name.vertex) {
  459. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  460. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  461. }
  462. else {
  463. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  464. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  465. }
  466. };
  467. ;
  468. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  469. var preparedSourceCode = this._processPrecision(sourceCode);
  470. if (this._engine.webGLVersion == 1) {
  471. callback(preparedSourceCode);
  472. return;
  473. }
  474. // Already converted
  475. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  476. callback(preparedSourceCode.replace("#version 300 es", ""));
  477. return;
  478. }
  479. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  480. // Remove extensions
  481. // #extension GL_OES_standard_derivatives : enable
  482. // #extension GL_EXT_shader_texture_lod : enable
  483. // #extension GL_EXT_frag_depth : enable
  484. // #extension GL_EXT_draw_buffers : require
  485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  486. var result = preparedSourceCode.replace(regex, "");
  487. // Migrate to GLSL v300
  488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  489. result = result.replace(/attribute[ \t]/g, "in ");
  490. result = result.replace(/[ \t]attribute/g, " in");
  491. if (isFragment) {
  492. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  494. result = result.replace(/texture2D\s*\(/g, "texture(");
  495. result = result.replace(/textureCube\s*\(/g, "texture(");
  496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  497. result = result.replace(/gl_FragColor/g, "glFragColor");
  498. result = result.replace(/gl_FragData/g, "glFragData");
  499. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  500. }
  501. callback(result);
  502. };
  503. Effect.prototype._processIncludes = function (sourceCode, callback) {
  504. var _this = this;
  505. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  506. var match = regex.exec(sourceCode);
  507. var returnValue = new String(sourceCode);
  508. while (match != null) {
  509. var includeFile = match[1];
  510. // Uniform declaration
  511. if (includeFile.indexOf("__decl__") !== -1) {
  512. includeFile = includeFile.replace(/__decl__/, "");
  513. if (this._engine.supportsUniformBuffers) {
  514. includeFile = includeFile.replace(/Vertex/, "Ubo");
  515. includeFile = includeFile.replace(/Fragment/, "Ubo");
  516. }
  517. includeFile = includeFile + "Declaration";
  518. }
  519. if (Effect.IncludesShadersStore[includeFile]) {
  520. // Substitution
  521. var includeContent = Effect.IncludesShadersStore[includeFile];
  522. if (match[2]) {
  523. var splits = match[3].split(",");
  524. for (var index = 0; index < splits.length; index += 2) {
  525. var source = new RegExp(splits[index], "g");
  526. var dest = splits[index + 1];
  527. includeContent = includeContent.replace(source, dest);
  528. }
  529. }
  530. if (match[4]) {
  531. var indexString = match[5];
  532. if (indexString.indexOf("..") !== -1) {
  533. var indexSplits = indexString.split("..");
  534. var minIndex = parseInt(indexSplits[0]);
  535. var maxIndex = parseInt(indexSplits[1]);
  536. var sourceIncludeContent = includeContent.slice(0);
  537. includeContent = "";
  538. if (isNaN(maxIndex)) {
  539. maxIndex = this._indexParameters[indexSplits[1]];
  540. }
  541. for (var i = minIndex; i < maxIndex; i++) {
  542. if (!this._engine.supportsUniformBuffers) {
  543. // Ubo replacement
  544. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  545. return p1 + "{X}";
  546. });
  547. }
  548. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  549. }
  550. }
  551. else {
  552. if (!this._engine.supportsUniformBuffers) {
  553. // Ubo replacement
  554. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  555. return p1 + "{X}";
  556. });
  557. }
  558. includeContent = includeContent.replace(/\{X\}/g, indexString);
  559. }
  560. }
  561. // Replace
  562. returnValue = returnValue.replace(match[0], includeContent);
  563. }
  564. else {
  565. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  566. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  567. Effect.IncludesShadersStore[includeFile] = fileContent;
  568. _this._processIncludes(returnValue, callback);
  569. });
  570. return;
  571. }
  572. match = regex.exec(sourceCode);
  573. }
  574. callback(returnValue);
  575. };
  576. Effect.prototype._processPrecision = function (source) {
  577. if (source.indexOf("precision highp float") === -1) {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = "precision mediump float;\n" + source;
  580. }
  581. else {
  582. source = "precision highp float;\n" + source;
  583. }
  584. }
  585. else {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  587. source = source.replace("precision highp float", "precision mediump float");
  588. }
  589. }
  590. return source;
  591. };
  592. /**
  593. * Recompiles the webGL program
  594. * @param vertexSourceCode The source code for the vertex shader.
  595. * @param fragmentSourceCode The source code for the fragment shader.
  596. * @param onCompiled Callback called when completed.
  597. * @param onError Callback called on error.
  598. */
  599. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  600. var _this = this;
  601. this._isReady = false;
  602. this._vertexSourceCodeOverride = vertexSourceCode;
  603. this._fragmentSourceCodeOverride = fragmentSourceCode;
  604. this.onError = function (effect, error) {
  605. if (onError) {
  606. onError(error);
  607. }
  608. };
  609. this.onCompiled = function () {
  610. var scenes = _this.getEngine().scenes;
  611. for (var i = 0; i < scenes.length; i++) {
  612. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  613. }
  614. if (onCompiled) {
  615. onCompiled(_this._program);
  616. }
  617. };
  618. this._fallbacks = null;
  619. this._prepareEffect();
  620. };
  621. /**
  622. * Gets the uniform locations of the the specified variable names
  623. * @param names THe names of the variables to lookup.
  624. * @returns Array of locations in the same order as variable names.
  625. */
  626. Effect.prototype.getSpecificUniformLocations = function (names) {
  627. var engine = this._engine;
  628. return engine.getUniforms(this._program, names);
  629. };
  630. /**
  631. * Prepares the effect
  632. */
  633. Effect.prototype._prepareEffect = function () {
  634. var attributesNames = this._attributesNames;
  635. var defines = this.defines;
  636. var fallbacks = this._fallbacks;
  637. this._valueCache = {};
  638. var previousProgram = this._program;
  639. try {
  640. var engine = this._engine;
  641. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  642. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  643. }
  644. else {
  645. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  646. }
  647. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  648. if (engine.supportsUniformBuffers) {
  649. for (var name in this._uniformBuffersNames) {
  650. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  651. }
  652. }
  653. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  654. this._attributes = engine.getAttributes(this._program, attributesNames);
  655. var index;
  656. for (index = 0; index < this._samplers.length; index++) {
  657. var sampler = this.getUniform(this._samplers[index]);
  658. if (sampler == null) {
  659. this._samplers.splice(index, 1);
  660. index--;
  661. }
  662. }
  663. engine.bindSamplers(this);
  664. this._compilationError = "";
  665. this._isReady = true;
  666. if (this.onCompiled) {
  667. this.onCompiled(this);
  668. }
  669. this.onCompileObservable.notifyObservers(this);
  670. this.onCompileObservable.clear();
  671. // Unbind mesh reference in fallbacks
  672. if (this._fallbacks) {
  673. this._fallbacks.unBindMesh();
  674. }
  675. if (previousProgram) {
  676. this.getEngine()._deleteProgram(previousProgram);
  677. }
  678. }
  679. catch (e) {
  680. this._compilationError = e.message;
  681. // Let's go through fallbacks then
  682. BABYLON.Tools.Error("Unable to compile effect:");
  683. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  684. return " " + uniform;
  685. }));
  686. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  687. return " " + attribute;
  688. }));
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. /**
  1369. * Ray from a pointer if availible (eg. 6dof controller)
  1370. */
  1371. _this.ray = null;
  1372. _this.skipOnPointerObservable = false;
  1373. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1374. return _this;
  1375. }
  1376. return PointerInfoPre;
  1377. }(PointerInfoBase));
  1378. BABYLON.PointerInfoPre = PointerInfoPre;
  1379. /**
  1380. * This type contains all the data related to a pointer event in Babylon.js.
  1381. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1382. */
  1383. var PointerInfo = /** @class */ (function (_super) {
  1384. __extends(PointerInfo, _super);
  1385. function PointerInfo(type, event, pickInfo) {
  1386. var _this = _super.call(this, type, event) || this;
  1387. _this.pickInfo = pickInfo;
  1388. return _this;
  1389. }
  1390. return PointerInfo;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfo = PointerInfo;
  1393. })(BABYLON || (BABYLON = {}));
  1394. //# sourceMappingURL=babylon.pointerEvents.js.map
  1395. var BABYLON;
  1396. (function (BABYLON) {
  1397. BABYLON.ToGammaSpace = 1 / 2.2;
  1398. BABYLON.ToLinearSpace = 2.2;
  1399. BABYLON.Epsilon = 0.001;
  1400. /**
  1401. * Class used to hold a RBG color
  1402. */
  1403. var Color3 = /** @class */ (function () {
  1404. /**
  1405. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1406. * @param r defines the red component (between 0 and 1, default is 0)
  1407. * @param g defines the green component (between 0 and 1, default is 0)
  1408. * @param b defines the blue component (between 0 and 1, default is 0)
  1409. */
  1410. function Color3(
  1411. /**
  1412. * Defines the red component (between 0 and 1, default is 0)
  1413. */
  1414. r,
  1415. /**
  1416. * Defines the green component (between 0 and 1, default is 0)
  1417. */
  1418. g,
  1419. /**
  1420. * Defines the blue component (between 0 and 1, default is 0)
  1421. */
  1422. b) {
  1423. if (r === void 0) { r = 0; }
  1424. if (g === void 0) { g = 0; }
  1425. if (b === void 0) { b = 0; }
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. }
  1430. /**
  1431. * Creates a string with the Color3 current values
  1432. * @returns the string representation of the Color3 object
  1433. */
  1434. Color3.prototype.toString = function () {
  1435. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1436. };
  1437. /**
  1438. * Returns the string "Color3"
  1439. * @returns "Color3"
  1440. */
  1441. Color3.prototype.getClassName = function () {
  1442. return "Color3";
  1443. };
  1444. /**
  1445. * Compute the Color3 hash code
  1446. * @returns an unique number that can be used to hash Color3 objects
  1447. */
  1448. Color3.prototype.getHashCode = function () {
  1449. var hash = this.r || 0;
  1450. hash = (hash * 397) ^ (this.g || 0);
  1451. hash = (hash * 397) ^ (this.b || 0);
  1452. return hash;
  1453. };
  1454. // Operators
  1455. /**
  1456. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1457. * @param array defines the array where to store the r,g,b components
  1458. * @param index defines an optional index in the target array to define where to start storing values
  1459. * @returns the current Color3 object
  1460. */
  1461. Color3.prototype.toArray = function (array, index) {
  1462. if (index === undefined) {
  1463. index = 0;
  1464. }
  1465. array[index] = this.r;
  1466. array[index + 1] = this.g;
  1467. array[index + 2] = this.b;
  1468. return this;
  1469. };
  1470. /**
  1471. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1472. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1473. * @returns a new {BABYLON.Color4} object
  1474. */
  1475. Color3.prototype.toColor4 = function (alpha) {
  1476. if (alpha === void 0) { alpha = 1; }
  1477. return new Color4(this.r, this.g, this.b, alpha);
  1478. };
  1479. /**
  1480. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1481. * @returns the new array
  1482. */
  1483. Color3.prototype.asArray = function () {
  1484. var result = new Array();
  1485. this.toArray(result, 0);
  1486. return result;
  1487. };
  1488. /**
  1489. * Returns the luminance value
  1490. * @returns a float value
  1491. */
  1492. Color3.prototype.toLuminance = function () {
  1493. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1494. };
  1495. /**
  1496. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1497. * @param otherColor defines the second operand
  1498. * @returns the new Color3 object
  1499. */
  1500. Color3.prototype.multiply = function (otherColor) {
  1501. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1502. };
  1503. /**
  1504. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1505. * @param otherColor defines the second operand
  1506. * @param result defines the Color3 object where to store the result
  1507. * @returns the current Color3
  1508. */
  1509. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1510. result.r = this.r * otherColor.r;
  1511. result.g = this.g * otherColor.g;
  1512. result.b = this.b * otherColor.b;
  1513. return this;
  1514. };
  1515. /**
  1516. * Determines equality between Color3 objects
  1517. * @param otherColor defines the second operand
  1518. * @returns true if the rgb values are equal to the given ones
  1519. */
  1520. Color3.prototype.equals = function (otherColor) {
  1521. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1522. };
  1523. /**
  1524. * Determines equality between the current Color3 object and a set of r,b,g values
  1525. * @param r defines the red component to check
  1526. * @param g defines the green component to check
  1527. * @param b defines the blue component to check
  1528. * @returns true if the rgb values are equal to the given ones
  1529. */
  1530. Color3.prototype.equalsFloats = function (r, g, b) {
  1531. return this.r === r && this.g === g && this.b === b;
  1532. };
  1533. /**
  1534. * Multiplies in place each rgb value by scale
  1535. * @param scale defines the scaling factor
  1536. * @returns the updated Color3
  1537. */
  1538. Color3.prototype.scale = function (scale) {
  1539. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1540. };
  1541. /**
  1542. * Multiplies the rgb values by scale and stores the result into "result"
  1543. * @param scale defines the scaling factor
  1544. * @param result defines the Color3 object where to store the result
  1545. * @returns the unmodified current Color3
  1546. */
  1547. Color3.prototype.scaleToRef = function (scale, result) {
  1548. result.r = this.r * scale;
  1549. result.g = this.g * scale;
  1550. result.b = this.b * scale;
  1551. return this;
  1552. };
  1553. /**
  1554. * Scale the current Color3 values by a factor and add the result to a given Color3
  1555. * @param scale defines the scale factor
  1556. * @param result defines color to store the result into
  1557. * @returns the unmodified current Color3
  1558. */
  1559. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1560. result.r += this.r * scale;
  1561. result.g += this.g * scale;
  1562. result.b += this.b * scale;
  1563. return this;
  1564. };
  1565. /**
  1566. * Clamps the rgb values by the min and max values and stores the result into "result"
  1567. * @param min defines minimum clamping value (default is 0)
  1568. * @param max defines maximum clamping value (default is 1)
  1569. * @param result defines color to store the result into
  1570. * @returns the original Color3
  1571. */
  1572. Color3.prototype.clampToRef = function (min, max, result) {
  1573. if (min === void 0) { min = 0; }
  1574. if (max === void 0) { max = 1; }
  1575. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1576. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1577. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1578. return this;
  1579. };
  1580. /**
  1581. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1582. * @param otherColor defines the second operand
  1583. * @returns the new Color3
  1584. */
  1585. Color3.prototype.add = function (otherColor) {
  1586. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1587. };
  1588. /**
  1589. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1590. * @param otherColor defines the second operand
  1591. * @param result defines Color3 object to store the result into
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.addToRef = function (otherColor, result) {
  1595. result.r = this.r + otherColor.r;
  1596. result.g = this.g + otherColor.g;
  1597. result.b = this.b + otherColor.b;
  1598. return this;
  1599. };
  1600. /**
  1601. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1602. * @param otherColor defines the second operand
  1603. * @returns the new Color3
  1604. */
  1605. Color3.prototype.subtract = function (otherColor) {
  1606. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1607. };
  1608. /**
  1609. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1610. * @param otherColor defines the second operand
  1611. * @param result defines Color3 object to store the result into
  1612. * @returns the unmodified current Color3
  1613. */
  1614. Color3.prototype.subtractToRef = function (otherColor, result) {
  1615. result.r = this.r - otherColor.r;
  1616. result.g = this.g - otherColor.g;
  1617. result.b = this.b - otherColor.b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Copy the current object
  1622. * @returns a new Color3 copied the current one
  1623. */
  1624. Color3.prototype.clone = function () {
  1625. return new Color3(this.r, this.g, this.b);
  1626. };
  1627. /**
  1628. * Copies the rgb values from the source in the current Color3
  1629. * @param source defines the source Color3 object
  1630. * @returns the updated Color3 object
  1631. */
  1632. Color3.prototype.copyFrom = function (source) {
  1633. this.r = source.r;
  1634. this.g = source.g;
  1635. this.b = source.b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.copyFromFloats = function (r, g, b) {
  1646. this.r = r;
  1647. this.g = g;
  1648. this.b = b;
  1649. return this;
  1650. };
  1651. /**
  1652. * Updates the Color3 rgb values from the given floats
  1653. * @param r defines the red component to read from
  1654. * @param g defines the green component to read from
  1655. * @param b defines the blue component to read from
  1656. * @returns the current Color3 object
  1657. */
  1658. Color3.prototype.set = function (r, g, b) {
  1659. return this.copyFromFloats(r, g, b);
  1660. };
  1661. /**
  1662. * Compute the Color3 hexadecimal code as a string
  1663. * @returns a string containing the hexadecimal representation of the Color3 object
  1664. */
  1665. Color3.prototype.toHexString = function () {
  1666. var intR = (this.r * 255) | 0;
  1667. var intG = (this.g * 255) | 0;
  1668. var intB = (this.b * 255) | 0;
  1669. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1670. };
  1671. /**
  1672. * Computes a new Color3 converted from the current one to linear space
  1673. * @returns a new Color3 object
  1674. */
  1675. Color3.prototype.toLinearSpace = function () {
  1676. var convertedColor = new Color3();
  1677. this.toLinearSpaceToRef(convertedColor);
  1678. return convertedColor;
  1679. };
  1680. /**
  1681. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1682. * @param convertedColor defines the Color3 object where to store the linear space version
  1683. * @returns the unmodified Color3
  1684. */
  1685. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1686. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1687. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1688. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1689. return this;
  1690. };
  1691. /**
  1692. * Computes a new Color3 converted from the current one to gamma space
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.prototype.toGammaSpace = function () {
  1696. var convertedColor = new Color3();
  1697. this.toGammaSpaceToRef(convertedColor);
  1698. return convertedColor;
  1699. };
  1700. /**
  1701. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1702. * @param convertedColor defines the Color3 object where to store the gamma space version
  1703. * @returns the unmodified Color3
  1704. */
  1705. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1706. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1707. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1708. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1709. return this;
  1710. };
  1711. // Statics
  1712. /**
  1713. * Creates a new Color3 from the string containing valid hexadecimal values
  1714. * @param hex defines a string containing valid hexadecimal values
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.FromHexString = function (hex) {
  1718. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1719. return new Color3(0, 0, 0);
  1720. }
  1721. var r = parseInt(hex.substring(1, 3), 16);
  1722. var g = parseInt(hex.substring(3, 5), 16);
  1723. var b = parseInt(hex.substring(5, 7), 16);
  1724. return Color3.FromInts(r, g, b);
  1725. };
  1726. /**
  1727. * Creates a new Vector3 from the starting index of the given array
  1728. * @param array defines the source array
  1729. * @param offset defines an offset in the source array
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromArray = function (array, offset) {
  1733. if (offset === void 0) { offset = 0; }
  1734. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1735. };
  1736. /**
  1737. * Creates a new Color3 from integer values (< 256)
  1738. * @param r defines the red component to read from (value between 0 and 255)
  1739. * @param g defines the green component to read from (value between 0 and 255)
  1740. * @param b defines the blue component to read from (value between 0 and 255)
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromInts = function (r, g, b) {
  1744. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1745. };
  1746. /**
  1747. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1748. * @param start defines the start Color3 value
  1749. * @param end defines the end Color3 value
  1750. * @param amount defines the gradient value between start and end
  1751. * @returns a new Color3 object
  1752. */
  1753. Color3.Lerp = function (start, end, amount) {
  1754. var r = start.r + ((end.r - start.r) * amount);
  1755. var g = start.g + ((end.g - start.g) * amount);
  1756. var b = start.b + ((end.b - start.b) * amount);
  1757. return new Color3(r, g, b);
  1758. };
  1759. /**
  1760. * Returns a Color3 value containing a red color
  1761. * @returns a new Color3 object
  1762. */
  1763. Color3.Red = function () { return new Color3(1, 0, 0); };
  1764. /**
  1765. * Returns a Color3 value containing a green color
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Green = function () { return new Color3(0, 1, 0); };
  1769. /**
  1770. * Returns a Color3 value containing a blue color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1774. /**
  1775. * Returns a Color3 value containing a black color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Black = function () { return new Color3(0, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a white color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.White = function () { return new Color3(1, 1, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a purple color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1789. /**
  1790. * Returns a Color3 value containing a magenta color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a yellow color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1799. /**
  1800. * Returns a Color3 value containing a gray color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a teal color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1809. /**
  1810. * Returns a Color3 value containing a random color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1814. return Color3;
  1815. }());
  1816. BABYLON.Color3 = Color3;
  1817. /**
  1818. * Class used to hold a RBGA color
  1819. */
  1820. var Color4 = /** @class */ (function () {
  1821. /**
  1822. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1823. * @param r defines the red component (between 0 and 1, default is 0)
  1824. * @param g defines the green component (between 0 and 1, default is 0)
  1825. * @param b defines the blue component (between 0 and 1, default is 0)
  1826. * @param a defines the alpha component (between 0 and 1, default is 1)
  1827. */
  1828. function Color4(
  1829. /**
  1830. * Defines the red component (between 0 and 1, default is 0)
  1831. */
  1832. r,
  1833. /**
  1834. * Defines the green component (between 0 and 1, default is 0)
  1835. */
  1836. g,
  1837. /**
  1838. * Defines the blue component (between 0 and 1, default is 0)
  1839. */
  1840. b,
  1841. /**
  1842. * Defines the alpha component (between 0 and 1, default is 1)
  1843. */
  1844. a) {
  1845. if (r === void 0) { r = 0; }
  1846. if (g === void 0) { g = 0; }
  1847. if (b === void 0) { b = 0; }
  1848. if (a === void 0) { a = 1; }
  1849. this.r = r;
  1850. this.g = g;
  1851. this.b = b;
  1852. this.a = a;
  1853. }
  1854. // Operators
  1855. /**
  1856. * Adds in place the given Color4 values to the current Color4 object
  1857. * @param right defines the second operand
  1858. * @returns the current updated Color4 object
  1859. */
  1860. Color4.prototype.addInPlace = function (right) {
  1861. this.r += right.r;
  1862. this.g += right.g;
  1863. this.b += right.b;
  1864. this.a += right.a;
  1865. return this;
  1866. };
  1867. /**
  1868. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1869. * @returns the new array
  1870. */
  1871. Color4.prototype.asArray = function () {
  1872. var result = new Array();
  1873. this.toArray(result, 0);
  1874. return result;
  1875. };
  1876. /**
  1877. * Stores from the starting index in the given array the Color4 successive values
  1878. * @param array defines the array where to store the r,g,b components
  1879. * @param index defines an optional index in the target array to define where to start storing values
  1880. * @returns the current Color4 object
  1881. */
  1882. Color4.prototype.toArray = function (array, index) {
  1883. if (index === undefined) {
  1884. index = 0;
  1885. }
  1886. array[index] = this.r;
  1887. array[index + 1] = this.g;
  1888. array[index + 2] = this.b;
  1889. array[index + 3] = this.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1894. * @param right defines the second operand
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.add = function (right) {
  1898. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1899. };
  1900. /**
  1901. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1902. * @param right defines the second operand
  1903. * @returns a new Color4 object
  1904. */
  1905. Color4.prototype.subtract = function (right) {
  1906. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1907. };
  1908. /**
  1909. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1910. * @param right defines the second operand
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the current Color4 object
  1913. */
  1914. Color4.prototype.subtractToRef = function (right, result) {
  1915. result.r = this.r - right.r;
  1916. result.g = this.g - right.g;
  1917. result.b = this.b - right.b;
  1918. result.a = this.a - right.a;
  1919. return this;
  1920. };
  1921. /**
  1922. * Creates a new Color4 with the current Color4 values multiplied by scale
  1923. * @param scale defines the scaling factor to apply
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.scale = function (scale) {
  1927. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1928. };
  1929. /**
  1930. * Multiplies the current Color4 values by scale and stores the result in "result"
  1931. * @param scale defines the scaling factor to apply
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the current unmodified Color4
  1934. */
  1935. Color4.prototype.scaleToRef = function (scale, result) {
  1936. result.r = this.r * scale;
  1937. result.g = this.g * scale;
  1938. result.b = this.b * scale;
  1939. result.a = this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Scale the current Color4 values by a factor and add the result to a given Color4
  1944. * @param scale defines the scale factor
  1945. * @param result defines the Color4 object where to store the result
  1946. * @returns the unmodified current Color4
  1947. */
  1948. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1949. result.r += this.r * scale;
  1950. result.g += this.g * scale;
  1951. result.b += this.b * scale;
  1952. result.a += this.a * scale;
  1953. return this;
  1954. };
  1955. /**
  1956. * Clamps the rgb values by the min and max values and stores the result into "result"
  1957. * @param min defines minimum clamping value (default is 0)
  1958. * @param max defines maximum clamping value (default is 1)
  1959. * @param result defines color to store the result into.
  1960. * @returns the cuurent Color4
  1961. */
  1962. Color4.prototype.clampToRef = function (min, max, result) {
  1963. if (min === void 0) { min = 0; }
  1964. if (max === void 0) { max = 1; }
  1965. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1966. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1967. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1968. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1969. return this;
  1970. };
  1971. /**
  1972. * Multipy an Color4 value by another and return a new Color4 object
  1973. * @param color defines the Color4 value to multiply by
  1974. * @returns a new Color4 object
  1975. */
  1976. Color4.prototype.multiply = function (color) {
  1977. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1978. };
  1979. /**
  1980. * Multipy a Color4 value by another and push the result in a reference value
  1981. * @param color defines the Color4 value to multiply by
  1982. * @param result defines the Color4 to fill the result in
  1983. * @returns the result Color4
  1984. */
  1985. Color4.prototype.multiplyToRef = function (color, result) {
  1986. result.r = this.r * color.r;
  1987. result.g = this.g * color.g;
  1988. result.b = this.b * color.b;
  1989. result.a = this.a * color.a;
  1990. return result;
  1991. };
  1992. /**
  1993. * Creates a string with the Color4 current values
  1994. * @returns the string representation of the Color4 object
  1995. */
  1996. Color4.prototype.toString = function () {
  1997. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1998. };
  1999. /**
  2000. * Returns the string "Color4"
  2001. * @returns "Color4"
  2002. */
  2003. Color4.prototype.getClassName = function () {
  2004. return "Color4";
  2005. };
  2006. /**
  2007. * Compute the Color4 hash code
  2008. * @returns an unique number that can be used to hash Color4 objects
  2009. */
  2010. Color4.prototype.getHashCode = function () {
  2011. var hash = this.r || 0;
  2012. hash = (hash * 397) ^ (this.g || 0);
  2013. hash = (hash * 397) ^ (this.b || 0);
  2014. hash = (hash * 397) ^ (this.a || 0);
  2015. return hash;
  2016. };
  2017. /**
  2018. * Creates a new Color4 copied from the current one
  2019. * @returns a new Color4 object
  2020. */
  2021. Color4.prototype.clone = function () {
  2022. return new Color4(this.r, this.g, this.b, this.a);
  2023. };
  2024. /**
  2025. * Copies the given Color4 values into the current one
  2026. * @param source defines the source Color4 object
  2027. * @returns the current updated Color4 object
  2028. */
  2029. Color4.prototype.copyFrom = function (source) {
  2030. this.r = source.r;
  2031. this.g = source.g;
  2032. this.b = source.b;
  2033. this.a = source.a;
  2034. return this;
  2035. };
  2036. /**
  2037. * Copies the given float values into the current one
  2038. * @param r defines the red component to read from
  2039. * @param g defines the green component to read from
  2040. * @param b defines the blue component to read from
  2041. * @param a defines the alpha component to read from
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2045. this.r = r;
  2046. this.g = g;
  2047. this.b = b;
  2048. this.a = a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the given float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.set = function (r, g, b, a) {
  2060. return this.copyFromFloats(r, g, b, a);
  2061. };
  2062. /**
  2063. * Compute the Color4 hexadecimal code as a string
  2064. * @returns a string containing the hexadecimal representation of the Color4 object
  2065. */
  2066. Color4.prototype.toHexString = function () {
  2067. var intR = (this.r * 255) | 0;
  2068. var intG = (this.g * 255) | 0;
  2069. var intB = (this.b * 255) | 0;
  2070. var intA = (this.a * 255) | 0;
  2071. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2072. };
  2073. /**
  2074. * Computes a new Color4 converted from the current one to linear space
  2075. * @returns a new Color4 object
  2076. */
  2077. Color4.prototype.toLinearSpace = function () {
  2078. var convertedColor = new Color4();
  2079. this.toLinearSpaceToRef(convertedColor);
  2080. return convertedColor;
  2081. };
  2082. /**
  2083. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2084. * @param convertedColor defines the Color4 object where to store the linear space version
  2085. * @returns the unmodified Color4
  2086. */
  2087. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2088. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2089. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2090. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2091. convertedColor.a = this.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Computes a new Color4 converted from the current one to gamma space
  2096. * @returns a new Color4 object
  2097. */
  2098. Color4.prototype.toGammaSpace = function () {
  2099. var convertedColor = new Color4();
  2100. this.toGammaSpaceToRef(convertedColor);
  2101. return convertedColor;
  2102. };
  2103. /**
  2104. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2105. * @param convertedColor defines the Color4 object where to store the gamma space version
  2106. * @returns the unmodified Color4
  2107. */
  2108. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2109. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2110. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2111. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2112. convertedColor.a = this.a;
  2113. return this;
  2114. };
  2115. // Statics
  2116. /**
  2117. * Creates a new Color4 from the string containing valid hexadecimal values
  2118. * @param hex defines a string containing valid hexadecimal values
  2119. * @returns a new Color4 object
  2120. */
  2121. Color4.FromHexString = function (hex) {
  2122. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2123. return new Color4(0.0, 0.0, 0.0, 0.0);
  2124. }
  2125. var r = parseInt(hex.substring(1, 3), 16);
  2126. var g = parseInt(hex.substring(3, 5), 16);
  2127. var b = parseInt(hex.substring(5, 7), 16);
  2128. var a = parseInt(hex.substring(7, 9), 16);
  2129. return Color4.FromInts(r, g, b, a);
  2130. };
  2131. /**
  2132. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2133. * @param left defines the start value
  2134. * @param right defines the end value
  2135. * @param amount defines the gradient factor
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.Lerp = function (left, right, amount) {
  2139. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2140. Color4.LerpToRef(left, right, amount, result);
  2141. return result;
  2142. };
  2143. /**
  2144. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2145. * @param left defines the start value
  2146. * @param right defines the end value
  2147. * @param amount defines the gradient factor
  2148. * @param result defines the Color4 object where to store data
  2149. */
  2150. Color4.LerpToRef = function (left, right, amount, result) {
  2151. result.r = left.r + (right.r - left.r) * amount;
  2152. result.g = left.g + (right.g - left.g) * amount;
  2153. result.b = left.b + (right.b - left.b) * amount;
  2154. result.a = left.a + (right.a - left.a) * amount;
  2155. };
  2156. /**
  2157. * Creates a new Color4 from the starting index element of the given array
  2158. * @param array defines the source array to read from
  2159. * @param offset defines the offset in the source array
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.FromArray = function (array, offset) {
  2163. if (offset === void 0) { offset = 0; }
  2164. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2165. };
  2166. /**
  2167. * Creates a new Color3 from integer values (< 256)
  2168. * @param r defines the red component to read from (value between 0 and 255)
  2169. * @param g defines the green component to read from (value between 0 and 255)
  2170. * @param b defines the blue component to read from (value between 0 and 255)
  2171. * @param a defines the alpha component to read from (value between 0 and 255)
  2172. * @returns a new Color3 object
  2173. */
  2174. Color4.FromInts = function (r, g, b, a) {
  2175. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2176. };
  2177. /**
  2178. * Check the content of a given array and convert it to an array containing RGBA data
  2179. * If the original array was already containing count * 4 values then it is returned directly
  2180. * @param colors defines the array to check
  2181. * @param count defines the number of RGBA data to expect
  2182. * @returns an array containing count * 4 values (RGBA)
  2183. */
  2184. Color4.CheckColors4 = function (colors, count) {
  2185. // Check if color3 was used
  2186. if (colors.length === count * 3) {
  2187. var colors4 = [];
  2188. for (var index = 0; index < colors.length; index += 3) {
  2189. var newIndex = (index / 3) * 4;
  2190. colors4[newIndex] = colors[index];
  2191. colors4[newIndex + 1] = colors[index + 1];
  2192. colors4[newIndex + 2] = colors[index + 2];
  2193. colors4[newIndex + 3] = 1.0;
  2194. }
  2195. return colors4;
  2196. }
  2197. return colors;
  2198. };
  2199. return Color4;
  2200. }());
  2201. BABYLON.Color4 = Color4;
  2202. /**
  2203. * Class representing a vector containing 2 coordinates
  2204. */
  2205. var Vector2 = /** @class */ (function () {
  2206. /**
  2207. * Creates a new Vector2 from the given x and y coordinates
  2208. * @param x defines the first coordinate
  2209. * @param y defines the second coordinate
  2210. */
  2211. function Vector2(
  2212. /** defines the first coordinate */
  2213. x,
  2214. /** defines the second coordinate */
  2215. y) {
  2216. if (x === void 0) { x = 0; }
  2217. if (y === void 0) { y = 0; }
  2218. this.x = x;
  2219. this.y = y;
  2220. }
  2221. /**
  2222. * Gets a string with the Vector2 coordinates
  2223. * @returns a string with the Vector2 coordinates
  2224. */
  2225. Vector2.prototype.toString = function () {
  2226. return "{X: " + this.x + " Y:" + this.y + "}";
  2227. };
  2228. /**
  2229. * Gets class name
  2230. * @returns the string "Vector2"
  2231. */
  2232. Vector2.prototype.getClassName = function () {
  2233. return "Vector2";
  2234. };
  2235. /**
  2236. * Gets current vector hash code
  2237. * @returns the Vector2 hash code as a number
  2238. */
  2239. Vector2.prototype.getHashCode = function () {
  2240. var hash = this.x || 0;
  2241. hash = (hash * 397) ^ (this.y || 0);
  2242. return hash;
  2243. };
  2244. // Operators
  2245. /**
  2246. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2247. * @param array defines the source array
  2248. * @param index defines the offset in source array
  2249. * @returns the current Vector2
  2250. */
  2251. Vector2.prototype.toArray = function (array, index) {
  2252. if (index === void 0) { index = 0; }
  2253. array[index] = this.x;
  2254. array[index + 1] = this.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Copy the current vector to an array
  2259. * @returns a new array with 2 elements: the Vector2 coordinates.
  2260. */
  2261. Vector2.prototype.asArray = function () {
  2262. var result = new Array();
  2263. this.toArray(result, 0);
  2264. return result;
  2265. };
  2266. /**
  2267. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2268. * @param source defines the source Vector2
  2269. * @returns the current updated Vector2
  2270. */
  2271. Vector2.prototype.copyFrom = function (source) {
  2272. this.x = source.x;
  2273. this.y = source.y;
  2274. return this;
  2275. };
  2276. /**
  2277. * Sets the Vector2 coordinates with the given floats
  2278. * @param x defines the first coordinate
  2279. * @param y defines the second coordinate
  2280. * @returns the current updated Vector2
  2281. */
  2282. Vector2.prototype.copyFromFloats = function (x, y) {
  2283. this.x = x;
  2284. this.y = y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Sets the Vector2 coordinates with the given floats
  2289. * @param x defines the first coordinate
  2290. * @param y defines the second coordinate
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.set = function (x, y) {
  2294. return this.copyFromFloats(x, y);
  2295. };
  2296. /**
  2297. * Add another vector with the current one
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2300. */
  2301. Vector2.prototype.add = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2306. * @param otherVector defines the other vector
  2307. * @param result defines the target vector
  2308. * @returns the unmodified current Vector2
  2309. */
  2310. Vector2.prototype.addToRef = function (otherVector, result) {
  2311. result.x = this.x + otherVector.x;
  2312. result.y = this.y + otherVector.y;
  2313. return this;
  2314. };
  2315. /**
  2316. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2317. * @param otherVector defines the other vector
  2318. * @returns the current updated Vector2
  2319. */
  2320. Vector2.prototype.addInPlace = function (otherVector) {
  2321. this.x += otherVector.x;
  2322. this.y += otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns a new Vector2
  2329. */
  2330. Vector2.prototype.addVector3 = function (otherVector) {
  2331. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2332. };
  2333. /**
  2334. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2335. * @param otherVector defines the other vector
  2336. * @returns a new Vector2
  2337. */
  2338. Vector2.prototype.subtract = function (otherVector) {
  2339. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2340. };
  2341. /**
  2342. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2343. * @param otherVector defines the other vector
  2344. * @param result defines the target vector
  2345. * @returns the unmodified current Vector2
  2346. */
  2347. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2348. result.x = this.x - otherVector.x;
  2349. result.y = this.y - otherVector.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2354. * @param otherVector defines the other vector
  2355. * @returns the current updated Vector2
  2356. */
  2357. Vector2.prototype.subtractInPlace = function (otherVector) {
  2358. this.x -= otherVector.x;
  2359. this.y -= otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Multiplies in place the current Vector2 coordinates by the given ones
  2364. * @param otherVector defines the other vector
  2365. * @returns the current updated Vector2
  2366. */
  2367. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2368. this.x *= otherVector.x;
  2369. this.y *= otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2
  2376. */
  2377. Vector2.prototype.multiply = function (otherVector) {
  2378. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2379. };
  2380. /**
  2381. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2382. * @param otherVector defines the other vector
  2383. * @param result defines the target vector
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. return this;
  2390. };
  2391. /**
  2392. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2393. * @param x defines the first coordinate
  2394. * @param y defines the second coordinate
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiplyByFloats = function (x, y) {
  2398. return new Vector2(this.x * x, this.y * y);
  2399. };
  2400. /**
  2401. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @returns a new Vector2
  2404. */
  2405. Vector2.prototype.divide = function (otherVector) {
  2406. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2407. };
  2408. /**
  2409. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2410. * @param otherVector defines the other vector
  2411. * @param result defines the target vector
  2412. * @returns the unmodified current Vector2
  2413. */
  2414. Vector2.prototype.divideToRef = function (otherVector, result) {
  2415. result.x = this.x / otherVector.x;
  2416. result.y = this.y / otherVector.y;
  2417. return this;
  2418. };
  2419. /**
  2420. * Divides the current Vector3 coordinates by the given ones
  2421. * @param otherVector defines the other vector
  2422. * @returns the current updated Vector2
  2423. */
  2424. Vector2.prototype.divideInPlace = function (otherVector) {
  2425. return this.divideToRef(otherVector, this);
  2426. };
  2427. /**
  2428. * Gets a new Vector2 with current Vector2 negated coordinates
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.negate = function () {
  2432. return new Vector2(-this.x, -this.y);
  2433. };
  2434. /**
  2435. * Multiply the Vector2 coordinates by scale
  2436. * @param scale defines the scaling factor
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.scaleInPlace = function (scale) {
  2440. this.x *= scale;
  2441. this.y *= scale;
  2442. return this;
  2443. };
  2444. /**
  2445. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2446. * @param scale defines the scaling factor
  2447. * @returns a new Vector2
  2448. */
  2449. Vector2.prototype.scale = function (scale) {
  2450. var result = new Vector2(0, 0);
  2451. this.scaleToRef(scale, result);
  2452. return result;
  2453. };
  2454. /**
  2455. * Scale the current Vector2 values by a factor to a given Vector2
  2456. * @param scale defines the scale factor
  2457. * @param result defines the Vector2 object where to store the result
  2458. * @returns the unmodified current Vector2
  2459. */
  2460. Vector2.prototype.scaleToRef = function (scale, result) {
  2461. result.x = this.x * scale;
  2462. result.y = this.y * scale;
  2463. return this;
  2464. };
  2465. /**
  2466. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2467. * @param scale defines the scale factor
  2468. * @param result defines the Vector2 object where to store the result
  2469. * @returns the unmodified current Vector2
  2470. */
  2471. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2472. result.x += this.x * scale;
  2473. result.y += this.y * scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Gets a boolean if two vectors are equals
  2478. * @param otherVector defines the other vector
  2479. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2480. */
  2481. Vector2.prototype.equals = function (otherVector) {
  2482. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2483. };
  2484. /**
  2485. * Gets a boolean if two vectors are equals (using an epsilon value)
  2486. * @param otherVector defines the other vector
  2487. * @param epsilon defines the minimal distance to consider equality
  2488. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2489. */
  2490. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2491. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2492. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2493. };
  2494. // Properties
  2495. /**
  2496. * Gets the length of the vector
  2497. * @returns the vector length (float)
  2498. */
  2499. Vector2.prototype.length = function () {
  2500. return Math.sqrt(this.x * this.x + this.y * this.y);
  2501. };
  2502. /**
  2503. * Gets the vector squared length
  2504. * @returns the vector squared length (float)
  2505. */
  2506. Vector2.prototype.lengthSquared = function () {
  2507. return (this.x * this.x + this.y * this.y);
  2508. };
  2509. // Methods
  2510. /**
  2511. * Normalize the vector
  2512. * @returns the current updated Vector2
  2513. */
  2514. Vector2.prototype.normalize = function () {
  2515. var len = this.length();
  2516. if (len === 0)
  2517. return this;
  2518. var num = 1.0 / len;
  2519. this.x *= num;
  2520. this.y *= num;
  2521. return this;
  2522. };
  2523. /**
  2524. * Gets a new Vector2 copied from the Vector2
  2525. * @returns a new Vector2
  2526. */
  2527. Vector2.prototype.clone = function () {
  2528. return new Vector2(this.x, this.y);
  2529. };
  2530. // Statics
  2531. /**
  2532. * Gets a new Vector2(0, 0)
  2533. * @returns a new Vector2
  2534. */
  2535. Vector2.Zero = function () {
  2536. return new Vector2(0, 0);
  2537. };
  2538. /**
  2539. * Gets a new Vector2(1, 1)
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.One = function () {
  2543. return new Vector2(1, 1);
  2544. };
  2545. /**
  2546. * Gets a new Vector2 set from the given index element of the given array
  2547. * @param array defines the data source
  2548. * @param offset defines the offset in the data source
  2549. * @returns a new Vector2
  2550. */
  2551. Vector2.FromArray = function (array, offset) {
  2552. if (offset === void 0) { offset = 0; }
  2553. return new Vector2(array[offset], array[offset + 1]);
  2554. };
  2555. /**
  2556. * Sets "result" from the given index element of the given array
  2557. * @param array defines the data source
  2558. * @param offset defines the offset in the data source
  2559. * @param result defines the target vector
  2560. */
  2561. Vector2.FromArrayToRef = function (array, offset, result) {
  2562. result.x = array[offset];
  2563. result.y = array[offset + 1];
  2564. };
  2565. /**
  2566. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2567. * @param value1 defines 1st point of control
  2568. * @param value2 defines 2nd point of control
  2569. * @param value3 defines 3rd point of control
  2570. * @param value4 defines 4th point of control
  2571. * @param amount defines the interpolation factor
  2572. * @returns a new Vector2
  2573. */
  2574. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2575. var squared = amount * amount;
  2576. var cubed = amount * squared;
  2577. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2578. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2579. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2580. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2581. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2582. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2583. return new Vector2(x, y);
  2584. };
  2585. /**
  2586. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2587. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2588. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2589. * @param value defines the value to clamp
  2590. * @param min defines the lower limit
  2591. * @param max defines the upper limit
  2592. * @returns a new Vector2
  2593. */
  2594. Vector2.Clamp = function (value, min, max) {
  2595. var x = value.x;
  2596. x = (x > max.x) ? max.x : x;
  2597. x = (x < min.x) ? min.x : x;
  2598. var y = value.y;
  2599. y = (y > max.y) ? max.y : y;
  2600. y = (y < min.y) ? min.y : y;
  2601. return new Vector2(x, y);
  2602. };
  2603. /**
  2604. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2605. * @param value1 defines the 1st control point
  2606. * @param tangent1 defines the outgoing tangent
  2607. * @param value2 defines the 2nd control point
  2608. * @param tangent2 defines the incoming tangent
  2609. * @param amount defines the interpolation factor
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2613. var squared = amount * amount;
  2614. var cubed = amount * squared;
  2615. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2616. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2617. var part3 = (cubed - (2.0 * squared)) + amount;
  2618. var part4 = cubed - squared;
  2619. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2620. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2621. return new Vector2(x, y);
  2622. };
  2623. /**
  2624. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2625. * @param start defines the start vector
  2626. * @param end defines the end vector
  2627. * @param amount defines the interpolation factor
  2628. * @returns a new Vector2
  2629. */
  2630. Vector2.Lerp = function (start, end, amount) {
  2631. var x = start.x + ((end.x - start.x) * amount);
  2632. var y = start.y + ((end.y - start.y) * amount);
  2633. return new Vector2(x, y);
  2634. };
  2635. /**
  2636. * Gets the dot product of the vector "left" and the vector "right"
  2637. * @param left defines first vector
  2638. * @param right defines second vector
  2639. * @returns the dot product (float)
  2640. */
  2641. Vector2.Dot = function (left, right) {
  2642. return left.x * right.x + left.y * right.y;
  2643. };
  2644. /**
  2645. * Returns a new Vector2 equal to the normalized given vector
  2646. * @param vector defines the vector to normalize
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Normalize = function (vector) {
  2650. var newVector = vector.clone();
  2651. newVector.normalize();
  2652. return newVector;
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2656. * @param left defines 1st vector
  2657. * @param right defines 2nd vector
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.Minimize = function (left, right) {
  2661. var x = (left.x < right.x) ? left.x : right.x;
  2662. var y = (left.y < right.y) ? left.y : right.y;
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2667. * @param left defines 1st vector
  2668. * @param right defines 2nd vector
  2669. * @returns a new Vector2
  2670. */
  2671. Vector2.Maximize = function (left, right) {
  2672. var x = (left.x > right.x) ? left.x : right.x;
  2673. var y = (left.y > right.y) ? left.y : right.y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2678. * @param vector defines the vector to transform
  2679. * @param transformation defines the matrix to apply
  2680. * @returns a new Vector2
  2681. */
  2682. Vector2.Transform = function (vector, transformation) {
  2683. var r = Vector2.Zero();
  2684. Vector2.TransformToRef(vector, transformation, r);
  2685. return r;
  2686. };
  2687. /**
  2688. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2689. * @param vector defines the vector to transform
  2690. * @param transformation defines the matrix to apply
  2691. * @param result defines the target vector
  2692. */
  2693. Vector2.TransformToRef = function (vector, transformation, result) {
  2694. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2695. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2696. result.x = x;
  2697. result.y = y;
  2698. };
  2699. /**
  2700. * Determines if a given vector is included in a triangle
  2701. * @param p defines the vector to test
  2702. * @param p0 defines 1st triangle point
  2703. * @param p1 defines 2nd triangle point
  2704. * @param p2 defines 3rd triangle point
  2705. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2706. */
  2707. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2708. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2709. var sign = a < 0 ? -1 : 1;
  2710. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2711. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2712. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2713. };
  2714. /**
  2715. * Gets the distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the distance between vectors
  2719. */
  2720. Vector2.Distance = function (value1, value2) {
  2721. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2722. };
  2723. /**
  2724. * Returns the squared distance between the vectors "value1" and "value2"
  2725. * @param value1 defines first vector
  2726. * @param value2 defines second vector
  2727. * @returns the squared distance between vectors
  2728. */
  2729. Vector2.DistanceSquared = function (value1, value2) {
  2730. var x = value1.x - value2.x;
  2731. var y = value1.y - value2.y;
  2732. return (x * x) + (y * y);
  2733. };
  2734. /**
  2735. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2736. * @param value1 defines first vector
  2737. * @param value2 defines second vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Center = function (value1, value2) {
  2741. var center = value1.add(value2);
  2742. center.scaleInPlace(0.5);
  2743. return center;
  2744. };
  2745. /**
  2746. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2747. * @param p defines the middle point
  2748. * @param segA defines one point of the segment
  2749. * @param segB defines the other point of the segment
  2750. * @returns the shortest distance
  2751. */
  2752. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2753. var l2 = Vector2.DistanceSquared(segA, segB);
  2754. if (l2 === 0.0) {
  2755. return Vector2.Distance(p, segA);
  2756. }
  2757. var v = segB.subtract(segA);
  2758. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2759. var proj = segA.add(v.multiplyByFloats(t, t));
  2760. return Vector2.Distance(p, proj);
  2761. };
  2762. return Vector2;
  2763. }());
  2764. BABYLON.Vector2 = Vector2;
  2765. /**
  2766. * Classed used to store (x,y,z) vector representation
  2767. * A Vector3 is the main object used in 3D geometry
  2768. * It can represent etiher the coordinates of a point the space, either a direction
  2769. * Reminder: Babylon.js uses a left handed forward facing system
  2770. */
  2771. var Vector3 = /** @class */ (function () {
  2772. /**
  2773. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2774. * @param x defines the first coordinates (on X axis)
  2775. * @param y defines the second coordinates (on Y axis)
  2776. * @param z defines the third coordinates (on Z axis)
  2777. */
  2778. function Vector3(
  2779. /**
  2780. * Defines the first coordinates (on X axis)
  2781. */
  2782. x,
  2783. /**
  2784. * Defines the second coordinates (on Y axis)
  2785. */
  2786. y,
  2787. /**
  2788. * Defines the third coordinates (on Z axis)
  2789. */
  2790. z) {
  2791. if (x === void 0) { x = 0; }
  2792. if (y === void 0) { y = 0; }
  2793. if (z === void 0) { z = 0; }
  2794. this.x = x;
  2795. this.y = y;
  2796. this.z = z;
  2797. }
  2798. /**
  2799. * Creates a string representation of the Vector3
  2800. * @returns a string with the Vector3 coordinates.
  2801. */
  2802. Vector3.prototype.toString = function () {
  2803. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2804. };
  2805. /**
  2806. * Gets the class name
  2807. * @returns the string "Vector3"
  2808. */
  2809. Vector3.prototype.getClassName = function () {
  2810. return "Vector3";
  2811. };
  2812. /**
  2813. * Creates the Vector3 hash code
  2814. * @returns a number which tends to be unique between Vector3 instances
  2815. */
  2816. Vector3.prototype.getHashCode = function () {
  2817. var hash = this.x || 0;
  2818. hash = (hash * 397) ^ (this.y || 0);
  2819. hash = (hash * 397) ^ (this.z || 0);
  2820. return hash;
  2821. };
  2822. // Operators
  2823. /**
  2824. * Creates an array containing three elements : the coordinates of the Vector3
  2825. * @returns a new array of numbers
  2826. */
  2827. Vector3.prototype.asArray = function () {
  2828. var result = [];
  2829. this.toArray(result, 0);
  2830. return result;
  2831. };
  2832. /**
  2833. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2834. * @param array defines the destination array
  2835. * @param index defines the offset in the destination array
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.toArray = function (array, index) {
  2839. if (index === void 0) { index = 0; }
  2840. array[index] = this.x;
  2841. array[index + 1] = this.y;
  2842. array[index + 2] = this.z;
  2843. return this;
  2844. };
  2845. /**
  2846. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2847. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2848. */
  2849. Vector3.prototype.toQuaternion = function () {
  2850. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2851. };
  2852. /**
  2853. * Adds the given vector to the current Vector3
  2854. * @param otherVector defines the second operand
  2855. * @returns the current updated Vector3
  2856. */
  2857. Vector3.prototype.addInPlace = function (otherVector) {
  2858. this.x += otherVector.x;
  2859. this.y += otherVector.y;
  2860. this.z += otherVector.z;
  2861. return this;
  2862. };
  2863. /**
  2864. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2865. * @param otherVector defines the second operand
  2866. * @returns the resulting Vector3
  2867. */
  2868. Vector3.prototype.add = function (otherVector) {
  2869. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2870. };
  2871. /**
  2872. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2873. * @param otherVector defines the second operand
  2874. * @param result defines the Vector3 object where to store the result
  2875. * @returns the current Vector3
  2876. */
  2877. Vector3.prototype.addToRef = function (otherVector, result) {
  2878. result.x = this.x + otherVector.x;
  2879. result.y = this.y + otherVector.y;
  2880. result.z = this.z + otherVector.z;
  2881. return this;
  2882. };
  2883. /**
  2884. * Subtract the given vector from the current Vector3
  2885. * @param otherVector defines the second operand
  2886. * @returns the current updated Vector3
  2887. */
  2888. Vector3.prototype.subtractInPlace = function (otherVector) {
  2889. this.x -= otherVector.x;
  2890. this.y -= otherVector.y;
  2891. this.z -= otherVector.z;
  2892. return this;
  2893. };
  2894. /**
  2895. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2896. * @param otherVector defines the second operand
  2897. * @returns the resulting Vector3
  2898. */
  2899. Vector3.prototype.subtract = function (otherVector) {
  2900. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2901. };
  2902. /**
  2903. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2904. * @param otherVector defines the second operand
  2905. * @param result defines the Vector3 object where to store the result
  2906. * @returns the current Vector3
  2907. */
  2908. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2909. result.x = this.x - otherVector.x;
  2910. result.y = this.y - otherVector.y;
  2911. result.z = this.z - otherVector.z;
  2912. return this;
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2916. * @param x defines the x coordinate of the operand
  2917. * @param y defines the y coordinate of the operand
  2918. * @param z defines the z coordinate of the operand
  2919. * @returns the resulting Vector3
  2920. */
  2921. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2922. return new Vector3(this.x - x, this.y - y, this.z - z);
  2923. };
  2924. /**
  2925. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2926. * @param x defines the x coordinate of the operand
  2927. * @param y defines the y coordinate of the operand
  2928. * @param z defines the z coordinate of the operand
  2929. * @param result defines the Vector3 object where to store the result
  2930. * @returns the current Vector3
  2931. */
  2932. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2933. result.x = this.x - x;
  2934. result.y = this.y - y;
  2935. result.z = this.z - z;
  2936. return this;
  2937. };
  2938. /**
  2939. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2940. * @returns a new Vector3
  2941. */
  2942. Vector3.prototype.negate = function () {
  2943. return new Vector3(-this.x, -this.y, -this.z);
  2944. };
  2945. /**
  2946. * Multiplies the Vector3 coordinates by the float "scale"
  2947. * @param scale defines the multiplier factor
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.scaleInPlace = function (scale) {
  2951. this.x *= scale;
  2952. this.y *= scale;
  2953. this.z *= scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2958. * @param scale defines the multiplier factor
  2959. * @returns a new Vector3
  2960. */
  2961. Vector3.prototype.scale = function (scale) {
  2962. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2963. };
  2964. /**
  2965. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2966. * @param scale defines the multiplier factor
  2967. * @param result defines the Vector3 object where to store the result
  2968. * @returns the current Vector3
  2969. */
  2970. Vector3.prototype.scaleToRef = function (scale, result) {
  2971. result.x = this.x * scale;
  2972. result.y = this.y * scale;
  2973. result.z = this.z * scale;
  2974. return this;
  2975. };
  2976. /**
  2977. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2978. * @param scale defines the scale factor
  2979. * @param result defines the Vector3 object where to store the result
  2980. * @returns the unmodified current Vector3
  2981. */
  2982. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2983. result.x += this.x * scale;
  2984. result.y += this.y * scale;
  2985. result.z += this.z * scale;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2990. * @param otherVector defines the second operand
  2991. * @returns true if both vectors are equals
  2992. */
  2993. Vector3.prototype.equals = function (otherVector) {
  2994. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2995. };
  2996. /**
  2997. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2998. * @param otherVector defines the second operand
  2999. * @param epsilon defines the minimal distance to define values as equals
  3000. * @returns true if both vectors are distant less than epsilon
  3001. */
  3002. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3003. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3004. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3005. };
  3006. /**
  3007. * Returns true if the current Vector3 coordinates equals the given floats
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @returns true if both vectors are equals
  3012. */
  3013. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3014. return this.x === x && this.y === y && this.z === z;
  3015. };
  3016. /**
  3017. * Multiplies the current Vector3 coordinates by the given ones
  3018. * @param otherVector defines the second operand
  3019. * @returns the current updated Vector3
  3020. */
  3021. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3022. this.x *= otherVector.x;
  3023. this.y *= otherVector.y;
  3024. this.z *= otherVector.z;
  3025. return this;
  3026. };
  3027. /**
  3028. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3029. * @param otherVector defines the second operand
  3030. * @returns the new Vector3
  3031. */
  3032. Vector3.prototype.multiply = function (otherVector) {
  3033. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3034. };
  3035. /**
  3036. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3037. * @param otherVector defines the second operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3042. result.x = this.x * otherVector.x;
  3043. result.y = this.y * otherVector.y;
  3044. result.z = this.z * otherVector.z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3049. * @param x defines the x coordinate of the operand
  3050. * @param y defines the y coordinate of the operand
  3051. * @param z defines the z coordinate of the operand
  3052. * @returns the new Vector3
  3053. */
  3054. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3055. return new Vector3(this.x * x, this.y * y, this.z * z);
  3056. };
  3057. /**
  3058. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3059. * @param otherVector defines the second operand
  3060. * @returns the new Vector3
  3061. */
  3062. Vector3.prototype.divide = function (otherVector) {
  3063. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3064. };
  3065. /**
  3066. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3067. * @param otherVector defines the second operand
  3068. * @param result defines the Vector3 object where to store the result
  3069. * @returns the current Vector3
  3070. */
  3071. Vector3.prototype.divideToRef = function (otherVector, result) {
  3072. result.x = this.x / otherVector.x;
  3073. result.y = this.y / otherVector.y;
  3074. result.z = this.z / otherVector.z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Divides the current Vector3 coordinates by the given ones.
  3079. * @param otherVector defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.divideInPlace = function (otherVector) {
  3083. return this.divideToRef(otherVector, this);
  3084. };
  3085. /**
  3086. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3087. * @param other defines the second operand
  3088. * @returns the current updated Vector3
  3089. */
  3090. Vector3.prototype.minimizeInPlace = function (other) {
  3091. if (other.x < this.x)
  3092. this.x = other.x;
  3093. if (other.y < this.y)
  3094. this.y = other.y;
  3095. if (other.z < this.z)
  3096. this.z = other.z;
  3097. return this;
  3098. };
  3099. /**
  3100. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3101. * @param other defines the second operand
  3102. * @returns the current updated Vector3
  3103. */
  3104. Vector3.prototype.maximizeInPlace = function (other) {
  3105. if (other.x > this.x)
  3106. this.x = other.x;
  3107. if (other.y > this.y)
  3108. this.y = other.y;
  3109. if (other.z > this.z)
  3110. this.z = other.z;
  3111. return this;
  3112. };
  3113. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3114. /**
  3115. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3116. */
  3117. get: function () {
  3118. var absX = Math.abs(this.x);
  3119. var absY = Math.abs(this.y);
  3120. if (absX !== absY) {
  3121. return true;
  3122. }
  3123. var absZ = Math.abs(this.z);
  3124. if (absX !== absZ) {
  3125. return true;
  3126. }
  3127. if (absY !== absZ) {
  3128. return true;
  3129. }
  3130. return false;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. // Properties
  3136. /**
  3137. * Gets the length of the Vector3
  3138. * @returns the length of the Vecto3
  3139. */
  3140. Vector3.prototype.length = function () {
  3141. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3142. };
  3143. /**
  3144. * Gets the squared length of the Vector3
  3145. * @returns squared length of the Vector3
  3146. */
  3147. Vector3.prototype.lengthSquared = function () {
  3148. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3149. };
  3150. /**
  3151. * Normalize the current Vector3.
  3152. * Please note that this is an in place operation.
  3153. * @returns the current updated Vector3
  3154. */
  3155. Vector3.prototype.normalize = function () {
  3156. var len = this.length();
  3157. if (len === 0 || len === 1.0)
  3158. return this;
  3159. var num = 1.0 / len;
  3160. this.x *= num;
  3161. this.y *= num;
  3162. this.z *= num;
  3163. return this;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to a new vector
  3167. * @returns the new Vector3
  3168. */
  3169. Vector3.prototype.normalizeToNew = function () {
  3170. var normalized = new Vector3(0, 0, 0);
  3171. this.normalizeToRef(normalized);
  3172. return normalized;
  3173. };
  3174. /**
  3175. * Normalize the current Vector3 to the reference
  3176. * @param reference define the Vector3 to update
  3177. * @returns the updated Vector3
  3178. */
  3179. Vector3.prototype.normalizeToRef = function (reference) {
  3180. var len = this.length();
  3181. if (len === 0 || len === 1.0) {
  3182. reference.set(this.x, this.y, this.z);
  3183. return reference;
  3184. }
  3185. var scale = 1.0 / len;
  3186. this.scaleToRef(scale, reference);
  3187. return reference;
  3188. };
  3189. /**
  3190. * Creates a new Vector3 copied from the current Vector3
  3191. * @returns the new Vector3
  3192. */
  3193. Vector3.prototype.clone = function () {
  3194. return new Vector3(this.x, this.y, this.z);
  3195. };
  3196. /**
  3197. * Copies the given vector coordinates to the current Vector3 ones
  3198. * @param source defines the source Vector3
  3199. * @returns the current updated Vector3
  3200. */
  3201. Vector3.prototype.copyFrom = function (source) {
  3202. this.x = source.x;
  3203. this.y = source.y;
  3204. this.z = source.z;
  3205. return this;
  3206. };
  3207. /**
  3208. * Copies the given floats to the current Vector3 coordinates
  3209. * @param x defines the x coordinate of the operand
  3210. * @param y defines the y coordinate of the operand
  3211. * @param z defines the z coordinate of the operand
  3212. * @returns the current updated Vector3
  3213. */
  3214. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3215. this.x = x;
  3216. this.y = y;
  3217. this.z = z;
  3218. return this;
  3219. };
  3220. /**
  3221. * Copies the given floats to the current Vector3 coordinates
  3222. * @param x defines the x coordinate of the operand
  3223. * @param y defines the y coordinate of the operand
  3224. * @param z defines the z coordinate of the operand
  3225. * @returns the current updated Vector3
  3226. */
  3227. Vector3.prototype.set = function (x, y, z) {
  3228. return this.copyFromFloats(x, y, z);
  3229. };
  3230. // Statics
  3231. /**
  3232. * Get the clip factor between two vectors
  3233. * @param vector0 defines the first operand
  3234. * @param vector1 defines the second operand
  3235. * @param axis defines the axis to use
  3236. * @param size defines the size along the axis
  3237. * @returns the clip factor
  3238. */
  3239. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3240. var d0 = Vector3.Dot(vector0, axis) - size;
  3241. var d1 = Vector3.Dot(vector1, axis) - size;
  3242. var s = d0 / (d0 - d1);
  3243. return s;
  3244. };
  3245. /**
  3246. * Get angle between two vectors
  3247. * @param vector0 angle between vector0 and vector1
  3248. * @param vector1 angle between vector0 and vector1
  3249. * @param normal direction of the normal
  3250. * @return the angle between vector0 and vector1
  3251. */
  3252. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3253. var v0 = vector0.clone().normalize();
  3254. var v1 = vector1.clone().normalize();
  3255. var dot = Vector3.Dot(v0, v1);
  3256. var n = Vector3.Cross(v0, v1);
  3257. if (Vector3.Dot(n, normal) > 0) {
  3258. return Math.acos(dot);
  3259. }
  3260. return -Math.acos(dot);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set from the index "offset" of the given array
  3264. * @param array defines the source array
  3265. * @param offset defines the offset in the source array
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.FromArray = function (array, offset) {
  3269. if (!offset) {
  3270. offset = 0;
  3271. }
  3272. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3273. };
  3274. /**
  3275. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3276. * This function is deprecated. Use FromArray instead
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @returns the new Vector3
  3280. */
  3281. Vector3.FromFloatArray = function (array, offset) {
  3282. return Vector3.FromArray(array, offset);
  3283. };
  3284. /**
  3285. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3286. * @param array defines the source array
  3287. * @param offset defines the offset in the source array
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.FromArrayToRef = function (array, offset, result) {
  3291. result.x = array[offset];
  3292. result.y = array[offset + 1];
  3293. result.z = array[offset + 2];
  3294. };
  3295. /**
  3296. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3297. * This function is deprecated. Use FromArrayToRef instead.
  3298. * @param array defines the source array
  3299. * @param offset defines the offset in the source array
  3300. * @param result defines the Vector3 where to store the result
  3301. */
  3302. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3303. return Vector3.FromArrayToRef(array, offset, result);
  3304. };
  3305. /**
  3306. * Sets the given vector "result" with the given floats.
  3307. * @param x defines the x coordinate of the source
  3308. * @param y defines the y coordinate of the source
  3309. * @param z defines the z coordinate of the source
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3313. result.x = x;
  3314. result.y = y;
  3315. result.z = z;
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3319. * @returns a new empty Vector3
  3320. */
  3321. Vector3.Zero = function () {
  3322. return new Vector3(0.0, 0.0, 0.0);
  3323. };
  3324. /**
  3325. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3326. * @returns a new unit Vector3
  3327. */
  3328. Vector3.One = function () {
  3329. return new Vector3(1.0, 1.0, 1.0);
  3330. };
  3331. /**
  3332. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3333. * @returns a new up Vector3
  3334. */
  3335. Vector3.Up = function () {
  3336. return new Vector3(0.0, 1.0, 0.0);
  3337. };
  3338. /**
  3339. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3340. * @returns a new down Vector3
  3341. */
  3342. Vector3.Down = function () {
  3343. return new Vector3(0.0, -1.0, 0.0);
  3344. };
  3345. /**
  3346. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3347. * @returns a new forward Vector3
  3348. */
  3349. Vector3.Forward = function () {
  3350. return new Vector3(0.0, 0.0, 1.0);
  3351. };
  3352. /**
  3353. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3354. * @returns a new right Vector3
  3355. */
  3356. Vector3.Right = function () {
  3357. return new Vector3(1.0, 0.0, 0.0);
  3358. };
  3359. /**
  3360. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3361. * @returns a new left Vector3
  3362. */
  3363. Vector3.Left = function () {
  3364. return new Vector3(-1.0, 0.0, 0.0);
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3368. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the transformed Vector3
  3372. */
  3373. Vector3.TransformCoordinates = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3380. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3389. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3390. result.x = x / w;
  3391. result.y = y / w;
  3392. result.z = z / w;
  3393. };
  3394. /**
  3395. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3396. * This method computes tranformed coordinates only, not transformed direction vectors
  3397. * @param x define the x coordinate of the source vector
  3398. * @param y define the y coordinate of the source vector
  3399. * @param z define the z coordinate of the source vector
  3400. * @param transformation defines the transformation matrix
  3401. * @param result defines the Vector3 where to store the result
  3402. */
  3403. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3404. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3405. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3406. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3407. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3408. result.x = rx / rw;
  3409. result.y = ry / rw;
  3410. result.z = rz / rw;
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param vector defines the Vector3 to transform
  3416. * @param transformation defines the transformation matrix
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.TransformNormal = function (vector, transformation) {
  3420. var result = Vector3.Zero();
  3421. Vector3.TransformNormalToRef(vector, transformation, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3426. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3427. * @param vector defines the Vector3 to transform
  3428. * @param transformation defines the transformation matrix
  3429. * @param result defines the Vector3 where to store the result
  3430. */
  3431. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3432. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3433. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3434. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3435. result.x = x;
  3436. result.y = y;
  3437. result.z = z;
  3438. };
  3439. /**
  3440. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3441. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3442. * @param x define the x coordinate of the source vector
  3443. * @param y define the y coordinate of the source vector
  3444. * @param z define the z coordinate of the source vector
  3445. * @param transformation defines the transformation matrix
  3446. * @param result defines the Vector3 where to store the result
  3447. */
  3448. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3449. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3450. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3451. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3452. };
  3453. /**
  3454. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3455. * @param value1 defines the first control point
  3456. * @param value2 defines the second control point
  3457. * @param value3 defines the third control point
  3458. * @param value4 defines the fourth control point
  3459. * @param amount defines the amount on the spline to use
  3460. * @returns the new Vector3
  3461. */
  3462. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3463. var squared = amount * amount;
  3464. var cubed = amount * squared;
  3465. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3466. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3467. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3468. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3469. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3470. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3471. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3472. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3473. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3474. return new Vector3(x, y, z);
  3475. };
  3476. /**
  3477. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3478. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3479. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3480. * @param value defines the current value
  3481. * @param min defines the lower range value
  3482. * @param max defines the upper range value
  3483. * @returns the new Vector3
  3484. */
  3485. Vector3.Clamp = function (value, min, max) {
  3486. var x = value.x;
  3487. x = (x > max.x) ? max.x : x;
  3488. x = (x < min.x) ? min.x : x;
  3489. var y = value.y;
  3490. y = (y > max.y) ? max.y : y;
  3491. y = (y < min.y) ? min.y : y;
  3492. var z = value.z;
  3493. z = (z > max.z) ? max.z : z;
  3494. z = (z < min.z) ? min.z : z;
  3495. return new Vector3(x, y, z);
  3496. };
  3497. /**
  3498. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3499. * @param value1 defines the first control point
  3500. * @param tangent1 defines the first tangent vector
  3501. * @param value2 defines the second control point
  3502. * @param tangent2 defines the second tangent vector
  3503. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3504. * @returns the new Vector3
  3505. */
  3506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3507. var squared = amount * amount;
  3508. var cubed = amount * squared;
  3509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3511. var part3 = (cubed - (2.0 * squared)) + amount;
  3512. var part4 = cubed - squared;
  3513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3516. return new Vector3(x, y, z);
  3517. };
  3518. /**
  3519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3520. * @param start defines the start value
  3521. * @param end defines the end value
  3522. * @param amount max defines amount between both (between 0 and 1)
  3523. * @returns the new Vector3
  3524. */
  3525. Vector3.Lerp = function (start, end, amount) {
  3526. var result = new Vector3(0, 0, 0);
  3527. Vector3.LerpToRef(start, end, amount, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3532. * @param start defines the start value
  3533. * @param end defines the end value
  3534. * @param amount max defines amount between both (between 0 and 1)
  3535. * @param result defines the Vector3 where to store the result
  3536. */
  3537. Vector3.LerpToRef = function (start, end, amount, result) {
  3538. result.x = start.x + ((end.x - start.x) * amount);
  3539. result.y = start.y + ((end.y - start.y) * amount);
  3540. result.z = start.z + ((end.z - start.z) * amount);
  3541. };
  3542. /**
  3543. * Returns the dot product (float) between the vectors "left" and "right"
  3544. * @param left defines the left operand
  3545. * @param right defines the right operand
  3546. * @returns the dot product
  3547. */
  3548. Vector3.Dot = function (left, right) {
  3549. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3553. * The cross product is then orthogonal to both "left" and "right"
  3554. * @param left defines the left operand
  3555. * @param right defines the right operand
  3556. * @returns the cross product
  3557. */
  3558. Vector3.Cross = function (left, right) {
  3559. var result = Vector3.Zero();
  3560. Vector3.CrossToRef(left, right, result);
  3561. return result;
  3562. };
  3563. /**
  3564. * Sets the given vector "result" with the cross product of "left" and "right"
  3565. * The cross product is then orthogonal to both "left" and "right"
  3566. * @param left defines the left operand
  3567. * @param right defines the right operand
  3568. * @param result defines the Vector3 where to store the result
  3569. */
  3570. Vector3.CrossToRef = function (left, right, result) {
  3571. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3572. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3573. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3574. result.copyFrom(MathTmp.Vector3[0]);
  3575. };
  3576. /**
  3577. * Returns a new Vector3 as the normalization of the given vector
  3578. * @param vector defines the Vector3 to normalize
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Normalize = function (vector) {
  3582. var result = Vector3.Zero();
  3583. Vector3.NormalizeToRef(vector, result);
  3584. return result;
  3585. };
  3586. /**
  3587. * Sets the given vector "result" with the normalization of the given first vector
  3588. * @param vector defines the Vector3 to normalize
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.NormalizeToRef = function (vector, result) {
  3592. result.copyFrom(vector);
  3593. result.normalize();
  3594. };
  3595. /**
  3596. * Project a Vector3 onto screen space
  3597. * @param vector defines the Vector3 to project
  3598. * @param world defines the world matrix to use
  3599. * @param transform defines the transform (view x projection) matrix to use
  3600. * @param viewport defines the screen viewport to use
  3601. * @returns the new Vector3
  3602. */
  3603. Vector3.Project = function (vector, world, transform, viewport) {
  3604. var cw = viewport.width;
  3605. var ch = viewport.height;
  3606. var cx = viewport.x;
  3607. var cy = viewport.y;
  3608. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3609. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3610. var matrix = MathTmp.Matrix[0];
  3611. world.multiplyToRef(transform, matrix);
  3612. matrix.multiplyToRef(viewportMatrix, matrix);
  3613. return Vector3.TransformCoordinates(vector, matrix);
  3614. };
  3615. /**
  3616. * Unproject from screen space to object space
  3617. * @param source defines the screen space Vector3 to use
  3618. * @param viewportWidth defines the current width of the viewport
  3619. * @param viewportHeight defines the current height of the viewport
  3620. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3621. * @param transform defines the transform (view x projection) matrix to use
  3622. * @returns the new Vector3
  3623. */
  3624. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3625. var matrix = MathTmp.Matrix[0];
  3626. world.multiplyToRef(transform, matrix);
  3627. matrix.invert();
  3628. source.x = source.x / viewportWidth * 2 - 1;
  3629. source.y = -(source.y / viewportHeight * 2 - 1);
  3630. var vector = Vector3.TransformCoordinates(source, matrix);
  3631. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3632. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3633. vector = vector.scale(1.0 / num);
  3634. }
  3635. return vector;
  3636. };
  3637. /**
  3638. * Unproject from screen space to object space
  3639. * @param source defines the screen space Vector3 to use
  3640. * @param viewportWidth defines the current width of the viewport
  3641. * @param viewportHeight defines the current height of the viewport
  3642. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3643. * @param view defines the view matrix to use
  3644. * @param projection defines the projection matrix to use
  3645. * @returns the new Vector3
  3646. */
  3647. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3648. var result = Vector3.Zero();
  3649. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3650. return result;
  3651. };
  3652. /**
  3653. * Unproject from screen space to object space
  3654. * @param source defines the screen space Vector3 to use
  3655. * @param viewportWidth defines the current width of the viewport
  3656. * @param viewportHeight defines the current height of the viewport
  3657. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3658. * @param view defines the view matrix to use
  3659. * @param projection defines the projection matrix to use
  3660. * @param result defines the Vector3 where to store the result
  3661. */
  3662. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3663. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3664. };
  3665. /**
  3666. * Unproject from screen space to object space
  3667. * @param sourceX defines the screen space x coordinate to use
  3668. * @param sourceY defines the screen space y coordinate to use
  3669. * @param sourceZ defines the screen space z coordinate to use
  3670. * @param viewportWidth defines the current width of the viewport
  3671. * @param viewportHeight defines the current height of the viewport
  3672. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3673. * @param view defines the view matrix to use
  3674. * @param projection defines the projection matrix to use
  3675. * @param result defines the Vector3 where to store the result
  3676. */
  3677. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3678. var matrix = MathTmp.Matrix[0];
  3679. world.multiplyToRef(view, matrix);
  3680. matrix.multiplyToRef(projection, matrix);
  3681. matrix.invert();
  3682. var screenSource = MathTmp.Vector3[0];
  3683. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3684. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3685. screenSource.z = 2 * sourceZ - 1.0;
  3686. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3687. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3688. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3689. result.scaleInPlace(1.0 / num);
  3690. }
  3691. };
  3692. /**
  3693. * Gets the minimal coordinate values between two Vector3
  3694. * @param left defines the first operand
  3695. * @param right defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Minimize = function (left, right) {
  3699. var min = left.clone();
  3700. min.minimizeInPlace(right);
  3701. return min;
  3702. };
  3703. /**
  3704. * Gets the maximal coordinate values between two Vector3
  3705. * @param left defines the first operand
  3706. * @param right defines the second operand
  3707. * @returns the new Vector3
  3708. */
  3709. Vector3.Maximize = function (left, right) {
  3710. var max = left.clone();
  3711. max.maximizeInPlace(right);
  3712. return max;
  3713. };
  3714. /**
  3715. * Returns the distance between the vectors "value1" and "value2"
  3716. * @param value1 defines the first operand
  3717. * @param value2 defines the second operand
  3718. * @returns the distance
  3719. */
  3720. Vector3.Distance = function (value1, value2) {
  3721. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3722. };
  3723. /**
  3724. * Returns the squared distance between the vectors "value1" and "value2"
  3725. * @param value1 defines the first operand
  3726. * @param value2 defines the second operand
  3727. * @returns the squared distance
  3728. */
  3729. Vector3.DistanceSquared = function (value1, value2) {
  3730. var x = value1.x - value2.x;
  3731. var y = value1.y - value2.y;
  3732. var z = value1.z - value2.z;
  3733. return (x * x) + (y * y) + (z * z);
  3734. };
  3735. /**
  3736. * Returns a new Vector3 located at the center between "value1" and "value2"
  3737. * @param value1 defines the first operand
  3738. * @param value2 defines the second operand
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.Center = function (value1, value2) {
  3742. var center = value1.add(value2);
  3743. center.scaleInPlace(0.5);
  3744. return center;
  3745. };
  3746. /**
  3747. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3748. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3749. * to something in order to rotate it from its local system to the given target system
  3750. * Note: axis1, axis2 and axis3 are normalized during this operation
  3751. * @param axis1 defines the first axis
  3752. * @param axis2 defines the second axis
  3753. * @param axis3 defines the third axis
  3754. * @returns a new Vector3
  3755. */
  3756. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3757. var rotation = Vector3.Zero();
  3758. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3759. return rotation;
  3760. };
  3761. /**
  3762. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3763. * @param axis1 defines the first axis
  3764. * @param axis2 defines the second axis
  3765. * @param axis3 defines the third axis
  3766. * @param ref defines the Vector3 where to store the result
  3767. */
  3768. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3769. var quat = MathTmp.Quaternion[0];
  3770. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3771. quat.toEulerAnglesToRef(ref);
  3772. };
  3773. return Vector3;
  3774. }());
  3775. BABYLON.Vector3 = Vector3;
  3776. //Vector4 class created for EulerAngle class conversion to Quaternion
  3777. var Vector4 = /** @class */ (function () {
  3778. /**
  3779. * Creates a Vector4 object from the given floats.
  3780. */
  3781. function Vector4(x, y, z, w) {
  3782. this.x = x;
  3783. this.y = y;
  3784. this.z = z;
  3785. this.w = w;
  3786. }
  3787. /**
  3788. * Returns the string with the Vector4 coordinates.
  3789. */
  3790. Vector4.prototype.toString = function () {
  3791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3792. };
  3793. /**
  3794. * Returns the string "Vector4".
  3795. */
  3796. Vector4.prototype.getClassName = function () {
  3797. return "Vector4";
  3798. };
  3799. /**
  3800. * Returns the Vector4 hash code.
  3801. */
  3802. Vector4.prototype.getHashCode = function () {
  3803. var hash = this.x || 0;
  3804. hash = (hash * 397) ^ (this.y || 0);
  3805. hash = (hash * 397) ^ (this.z || 0);
  3806. hash = (hash * 397) ^ (this.w || 0);
  3807. return hash;
  3808. };
  3809. // Operators
  3810. /**
  3811. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3812. */
  3813. Vector4.prototype.asArray = function () {
  3814. var result = new Array();
  3815. this.toArray(result, 0);
  3816. return result;
  3817. };
  3818. /**
  3819. * Populates the given array from the given index with the Vector4 coordinates.
  3820. * Returns the Vector4.
  3821. */
  3822. Vector4.prototype.toArray = function (array, index) {
  3823. if (index === undefined) {
  3824. index = 0;
  3825. }
  3826. array[index] = this.x;
  3827. array[index + 1] = this.y;
  3828. array[index + 2] = this.z;
  3829. array[index + 3] = this.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Adds the given vector to the current Vector4.
  3834. * Returns the updated Vector4.
  3835. */
  3836. Vector4.prototype.addInPlace = function (otherVector) {
  3837. this.x += otherVector.x;
  3838. this.y += otherVector.y;
  3839. this.z += otherVector.z;
  3840. this.w += otherVector.w;
  3841. return this;
  3842. };
  3843. /**
  3844. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3845. */
  3846. Vector4.prototype.add = function (otherVector) {
  3847. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3848. };
  3849. /**
  3850. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3851. * Returns the current Vector4.
  3852. */
  3853. Vector4.prototype.addToRef = function (otherVector, result) {
  3854. result.x = this.x + otherVector.x;
  3855. result.y = this.y + otherVector.y;
  3856. result.z = this.z + otherVector.z;
  3857. result.w = this.w + otherVector.w;
  3858. return this;
  3859. };
  3860. /**
  3861. * Subtract in place the given vector from the current Vector4.
  3862. * Returns the updated Vector4.
  3863. */
  3864. Vector4.prototype.subtractInPlace = function (otherVector) {
  3865. this.x -= otherVector.x;
  3866. this.y -= otherVector.y;
  3867. this.z -= otherVector.z;
  3868. this.w -= otherVector.w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3873. */
  3874. Vector4.prototype.subtract = function (otherVector) {
  3875. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3876. };
  3877. /**
  3878. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3879. * Returns the current Vector4.
  3880. */
  3881. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3882. result.x = this.x - otherVector.x;
  3883. result.y = this.y - otherVector.y;
  3884. result.z = this.z - otherVector.z;
  3885. result.w = this.w - otherVector.w;
  3886. return this;
  3887. };
  3888. /**
  3889. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3890. */
  3891. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3892. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3893. };
  3894. /**
  3895. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3896. * Returns the current Vector4.
  3897. */
  3898. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3899. result.x = this.x - x;
  3900. result.y = this.y - y;
  3901. result.z = this.z - z;
  3902. result.w = this.w - w;
  3903. return this;
  3904. };
  3905. /**
  3906. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3907. */
  3908. Vector4.prototype.negate = function () {
  3909. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3910. };
  3911. /**
  3912. * Multiplies the current Vector4 coordinates by scale (float).
  3913. * Returns the updated Vector4.
  3914. */
  3915. Vector4.prototype.scaleInPlace = function (scale) {
  3916. this.x *= scale;
  3917. this.y *= scale;
  3918. this.z *= scale;
  3919. this.w *= scale;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3924. */
  3925. Vector4.prototype.scale = function (scale) {
  3926. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3927. };
  3928. /**
  3929. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3930. * Returns the current Vector4.
  3931. */
  3932. Vector4.prototype.scaleToRef = function (scale, result) {
  3933. result.x = this.x * scale;
  3934. result.y = this.y * scale;
  3935. result.z = this.z * scale;
  3936. result.w = this.w * scale;
  3937. return this;
  3938. };
  3939. /**
  3940. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3941. * @param scale defines the scale factor
  3942. * @param result defines the Vector4 object where to store the result
  3943. * @returns the unmodified current Vector4
  3944. */
  3945. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3946. result.x += this.x * scale;
  3947. result.y += this.y * scale;
  3948. result.z += this.z * scale;
  3949. result.w += this.w * scale;
  3950. return this;
  3951. };
  3952. /**
  3953. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3954. */
  3955. Vector4.prototype.equals = function (otherVector) {
  3956. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3957. };
  3958. /**
  3959. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3960. */
  3961. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3962. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3963. return otherVector
  3964. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3965. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3966. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3967. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3968. };
  3969. /**
  3970. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3971. */
  3972. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3973. return this.x === x && this.y === y && this.z === z && this.w === w;
  3974. };
  3975. /**
  3976. * Multiplies in place the current Vector4 by the given one.
  3977. * Returns the updated Vector4.
  3978. */
  3979. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3980. this.x *= otherVector.x;
  3981. this.y *= otherVector.y;
  3982. this.z *= otherVector.z;
  3983. this.w *= otherVector.w;
  3984. return this;
  3985. };
  3986. /**
  3987. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3988. */
  3989. Vector4.prototype.multiply = function (otherVector) {
  3990. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3991. };
  3992. /**
  3993. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3994. * Returns the current Vector4.
  3995. */
  3996. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3997. result.x = this.x * otherVector.x;
  3998. result.y = this.y * otherVector.y;
  3999. result.z = this.z * otherVector.z;
  4000. result.w = this.w * otherVector.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4005. */
  4006. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4007. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4008. };
  4009. /**
  4010. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4011. */
  4012. Vector4.prototype.divide = function (otherVector) {
  4013. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4014. };
  4015. /**
  4016. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4017. * Returns the current Vector4.
  4018. */
  4019. Vector4.prototype.divideToRef = function (otherVector, result) {
  4020. result.x = this.x / otherVector.x;
  4021. result.y = this.y / otherVector.y;
  4022. result.z = this.z / otherVector.z;
  4023. result.w = this.w / otherVector.w;
  4024. return this;
  4025. };
  4026. /**
  4027. * Divides the current Vector3 coordinates by the given ones.
  4028. * @returns the updated Vector3.
  4029. */
  4030. Vector4.prototype.divideInPlace = function (otherVector) {
  4031. return this.divideToRef(otherVector, this);
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4035. * @param other defines the second operand
  4036. * @returns the current updated Vector4
  4037. */
  4038. Vector4.prototype.minimizeInPlace = function (other) {
  4039. if (other.x < this.x)
  4040. this.x = other.x;
  4041. if (other.y < this.y)
  4042. this.y = other.y;
  4043. if (other.z < this.z)
  4044. this.z = other.z;
  4045. if (other.w < this.w)
  4046. this.w = other.w;
  4047. return this;
  4048. };
  4049. /**
  4050. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4051. * @param other defines the second operand
  4052. * @returns the current updated Vector4
  4053. */
  4054. Vector4.prototype.maximizeInPlace = function (other) {
  4055. if (other.x > this.x)
  4056. this.x = other.x;
  4057. if (other.y > this.y)
  4058. this.y = other.y;
  4059. if (other.z > this.z)
  4060. this.z = other.z;
  4061. if (other.w > this.w)
  4062. this.w = other.w;
  4063. return this;
  4064. };
  4065. // Properties
  4066. /**
  4067. * Returns the Vector4 length (float).
  4068. */
  4069. Vector4.prototype.length = function () {
  4070. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4071. };
  4072. /**
  4073. * Returns the Vector4 squared length (float).
  4074. */
  4075. Vector4.prototype.lengthSquared = function () {
  4076. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4077. };
  4078. // Methods
  4079. /**
  4080. * Normalizes in place the Vector4.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.normalize = function () {
  4084. var len = this.length();
  4085. if (len === 0)
  4086. return this;
  4087. var num = 1.0 / len;
  4088. this.x *= num;
  4089. this.y *= num;
  4090. this.z *= num;
  4091. this.w *= num;
  4092. return this;
  4093. };
  4094. /**
  4095. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4096. */
  4097. Vector4.prototype.toVector3 = function () {
  4098. return new Vector3(this.x, this.y, this.z);
  4099. };
  4100. /**
  4101. * Returns a new Vector4 copied from the current one.
  4102. */
  4103. Vector4.prototype.clone = function () {
  4104. return new Vector4(this.x, this.y, this.z, this.w);
  4105. };
  4106. /**
  4107. * Updates the current Vector4 with the given one coordinates.
  4108. * Returns the updated Vector4.
  4109. */
  4110. Vector4.prototype.copyFrom = function (source) {
  4111. this.x = source.x;
  4112. this.y = source.y;
  4113. this.z = source.z;
  4114. this.w = source.w;
  4115. return this;
  4116. };
  4117. /**
  4118. * Updates the current Vector4 coordinates with the given floats.
  4119. * Returns the updated Vector4.
  4120. */
  4121. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4122. this.x = x;
  4123. this.y = y;
  4124. this.z = z;
  4125. this.w = w;
  4126. return this;
  4127. };
  4128. /**
  4129. * Updates the current Vector4 coordinates with the given floats.
  4130. * Returns the updated Vector4.
  4131. */
  4132. Vector4.prototype.set = function (x, y, z, w) {
  4133. return this.copyFromFloats(x, y, z, w);
  4134. };
  4135. // Statics
  4136. /**
  4137. * Returns a new Vector4 set from the starting index of the given array.
  4138. */
  4139. Vector4.FromArray = function (array, offset) {
  4140. if (!offset) {
  4141. offset = 0;
  4142. }
  4143. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4144. };
  4145. /**
  4146. * Updates the given vector "result" from the starting index of the given array.
  4147. */
  4148. Vector4.FromArrayToRef = function (array, offset, result) {
  4149. result.x = array[offset];
  4150. result.y = array[offset + 1];
  4151. result.z = array[offset + 2];
  4152. result.w = array[offset + 3];
  4153. };
  4154. /**
  4155. * Updates the given vector "result" from the starting index of the given Float32Array.
  4156. */
  4157. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4158. Vector4.FromArrayToRef(array, offset, result);
  4159. };
  4160. /**
  4161. * Updates the given vector "result" coordinates from the given floats.
  4162. */
  4163. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4164. result.x = x;
  4165. result.y = y;
  4166. result.z = z;
  4167. result.w = w;
  4168. };
  4169. /**
  4170. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4171. */
  4172. Vector4.Zero = function () {
  4173. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4174. };
  4175. /**
  4176. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4177. */
  4178. Vector4.One = function () {
  4179. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4180. };
  4181. /**
  4182. * Returns a new normalized Vector4 from the given one.
  4183. */
  4184. Vector4.Normalize = function (vector) {
  4185. var result = Vector4.Zero();
  4186. Vector4.NormalizeToRef(vector, result);
  4187. return result;
  4188. };
  4189. /**
  4190. * Updates the given vector "result" from the normalization of the given one.
  4191. */
  4192. Vector4.NormalizeToRef = function (vector, result) {
  4193. result.copyFrom(vector);
  4194. result.normalize();
  4195. };
  4196. Vector4.Minimize = function (left, right) {
  4197. var min = left.clone();
  4198. min.minimizeInPlace(right);
  4199. return min;
  4200. };
  4201. Vector4.Maximize = function (left, right) {
  4202. var max = left.clone();
  4203. max.maximizeInPlace(right);
  4204. return max;
  4205. };
  4206. /**
  4207. * Returns the distance (float) between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Distance = function (value1, value2) {
  4210. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4211. };
  4212. /**
  4213. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4214. */
  4215. Vector4.DistanceSquared = function (value1, value2) {
  4216. var x = value1.x - value2.x;
  4217. var y = value1.y - value2.y;
  4218. var z = value1.z - value2.z;
  4219. var w = value1.w - value2.w;
  4220. return (x * x) + (y * y) + (z * z) + (w * w);
  4221. };
  4222. /**
  4223. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4224. */
  4225. Vector4.Center = function (value1, value2) {
  4226. var center = value1.add(value2);
  4227. center.scaleInPlace(0.5);
  4228. return center;
  4229. };
  4230. /**
  4231. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4232. * This methods computes transformed normalized direction vectors only.
  4233. */
  4234. Vector4.TransformNormal = function (vector, transformation) {
  4235. var result = Vector4.Zero();
  4236. Vector4.TransformNormalToRef(vector, transformation, result);
  4237. return result;
  4238. };
  4239. /**
  4240. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4241. * This methods computes transformed normalized direction vectors only.
  4242. */
  4243. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4244. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4245. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4246. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4247. result.x = x;
  4248. result.y = y;
  4249. result.z = z;
  4250. result.w = vector.w;
  4251. };
  4252. /**
  4253. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4254. * This methods computes transformed normalized direction vectors only.
  4255. */
  4256. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4257. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4258. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4259. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4260. result.w = w;
  4261. };
  4262. return Vector4;
  4263. }());
  4264. BABYLON.Vector4 = Vector4;
  4265. var Size = /** @class */ (function () {
  4266. /**
  4267. * Creates a Size object from the given width and height (floats).
  4268. */
  4269. function Size(width, height) {
  4270. this.width = width;
  4271. this.height = height;
  4272. }
  4273. // Returns a string with the Size width and height.
  4274. Size.prototype.toString = function () {
  4275. return "{W: " + this.width + ", H: " + this.height + "}";
  4276. };
  4277. /**
  4278. * Returns the string "Size"
  4279. */
  4280. Size.prototype.getClassName = function () {
  4281. return "Size";
  4282. };
  4283. /**
  4284. * Returns the Size hash code.
  4285. */
  4286. Size.prototype.getHashCode = function () {
  4287. var hash = this.width || 0;
  4288. hash = (hash * 397) ^ (this.height || 0);
  4289. return hash;
  4290. };
  4291. /**
  4292. * Updates the current size from the given one.
  4293. * Returns the updated Size.
  4294. */
  4295. Size.prototype.copyFrom = function (src) {
  4296. this.width = src.width;
  4297. this.height = src.height;
  4298. };
  4299. /**
  4300. * Updates in place the current Size from the given floats.
  4301. * Returns the updated Size.
  4302. */
  4303. Size.prototype.copyFromFloats = function (width, height) {
  4304. this.width = width;
  4305. this.height = height;
  4306. return this;
  4307. };
  4308. /**
  4309. * Updates in place the current Size from the given floats.
  4310. * Returns the updated Size.
  4311. */
  4312. Size.prototype.set = function (width, height) {
  4313. return this.copyFromFloats(width, height);
  4314. };
  4315. /**
  4316. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4317. */
  4318. Size.prototype.multiplyByFloats = function (w, h) {
  4319. return new Size(this.width * w, this.height * h);
  4320. };
  4321. /**
  4322. * Returns a new Size copied from the given one.
  4323. */
  4324. Size.prototype.clone = function () {
  4325. return new Size(this.width, this.height);
  4326. };
  4327. /**
  4328. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4329. */
  4330. Size.prototype.equals = function (other) {
  4331. if (!other) {
  4332. return false;
  4333. }
  4334. return (this.width === other.width) && (this.height === other.height);
  4335. };
  4336. Object.defineProperty(Size.prototype, "surface", {
  4337. /**
  4338. * Returns the surface of the Size : width * height (float).
  4339. */
  4340. get: function () {
  4341. return this.width * this.height;
  4342. },
  4343. enumerable: true,
  4344. configurable: true
  4345. });
  4346. /**
  4347. * Returns a new Size set to (0.0, 0.0)
  4348. */
  4349. Size.Zero = function () {
  4350. return new Size(0.0, 0.0);
  4351. };
  4352. /**
  4353. * Returns a new Size set as the addition result of the current Size and the given one.
  4354. */
  4355. Size.prototype.add = function (otherSize) {
  4356. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4357. return r;
  4358. };
  4359. /**
  4360. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4361. */
  4362. Size.prototype.subtract = function (otherSize) {
  4363. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4364. return r;
  4365. };
  4366. /**
  4367. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4368. */
  4369. Size.Lerp = function (start, end, amount) {
  4370. var w = start.width + ((end.width - start.width) * amount);
  4371. var h = start.height + ((end.height - start.height) * amount);
  4372. return new Size(w, h);
  4373. };
  4374. return Size;
  4375. }());
  4376. BABYLON.Size = Size;
  4377. /**
  4378. * Class used to store quaternion data
  4379. * @see https://en.wikipedia.org/wiki/Quaternion
  4380. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4381. */
  4382. var Quaternion = /** @class */ (function () {
  4383. /**
  4384. * Creates a new Quaternion from the given floats
  4385. * @param x defines the first component (0 by default)
  4386. * @param y defines the second component (0 by default)
  4387. * @param z defines the third component (0 by default)
  4388. * @param w defines the fourth component (1.0 by default)
  4389. */
  4390. function Quaternion(
  4391. /** defines the first component (0 by default) */
  4392. x,
  4393. /** defines the second component (0 by default) */
  4394. y,
  4395. /** defines the third component (0 by default) */
  4396. z,
  4397. /** defines the fourth component (1.0 by default) */
  4398. w) {
  4399. if (x === void 0) { x = 0.0; }
  4400. if (y === void 0) { y = 0.0; }
  4401. if (z === void 0) { z = 0.0; }
  4402. if (w === void 0) { w = 1.0; }
  4403. this.x = x;
  4404. this.y = y;
  4405. this.z = z;
  4406. this.w = w;
  4407. }
  4408. /**
  4409. * Gets a string representation for the current quaternion
  4410. * @returns a string with the Quaternion coordinates
  4411. */
  4412. Quaternion.prototype.toString = function () {
  4413. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4414. };
  4415. /**
  4416. * Gets the class name of the quaternion
  4417. * @returns the string "Quaternion"
  4418. */
  4419. Quaternion.prototype.getClassName = function () {
  4420. return "Quaternion";
  4421. };
  4422. /**
  4423. * Gets a hash code for this quaternion
  4424. * @returns the quaternion hash code
  4425. */
  4426. Quaternion.prototype.getHashCode = function () {
  4427. var hash = this.x || 0;
  4428. hash = (hash * 397) ^ (this.y || 0);
  4429. hash = (hash * 397) ^ (this.z || 0);
  4430. hash = (hash * 397) ^ (this.w || 0);
  4431. return hash;
  4432. };
  4433. /**
  4434. * Copy the quaternion to an array
  4435. * @returns a new array populated with 4 elements from the quaternion coordinates
  4436. */
  4437. Quaternion.prototype.asArray = function () {
  4438. return [this.x, this.y, this.z, this.w];
  4439. };
  4440. /**
  4441. * Check if two quaternions are equals
  4442. * @param otherQuaternion defines the second operand
  4443. * @return true if the current quaternion and the given one coordinates are strictly equals
  4444. */
  4445. Quaternion.prototype.equals = function (otherQuaternion) {
  4446. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4447. };
  4448. /**
  4449. * Clone the current quaternion
  4450. * @returns a new quaternion copied from the current one
  4451. */
  4452. Quaternion.prototype.clone = function () {
  4453. return new Quaternion(this.x, this.y, this.z, this.w);
  4454. };
  4455. /**
  4456. * Copy a quaternion to the current one
  4457. * @param other defines the other quaternion
  4458. * @returns the updated current quaternion
  4459. */
  4460. Quaternion.prototype.copyFrom = function (other) {
  4461. this.x = other.x;
  4462. this.y = other.y;
  4463. this.z = other.z;
  4464. this.w = other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Updates the current quaternion with the given float coordinates
  4469. * @param x defines the x coordinate
  4470. * @param y defines the y coordinate
  4471. * @param z defines the z coordinate
  4472. * @param w defines the w coordinate
  4473. * @returns the updated current quaternion
  4474. */
  4475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4476. this.x = x;
  4477. this.y = y;
  4478. this.z = z;
  4479. this.w = w;
  4480. return this;
  4481. };
  4482. /**
  4483. * Updates the current quaternion from the given float coordinates
  4484. * @param x defines the x coordinate
  4485. * @param y defines the y coordinate
  4486. * @param z defines the z coordinate
  4487. * @param w defines the w coordinate
  4488. * @returns the updated current quaternion
  4489. */
  4490. Quaternion.prototype.set = function (x, y, z, w) {
  4491. return this.copyFromFloats(x, y, z, w);
  4492. };
  4493. /**
  4494. * Adds two quaternions
  4495. * @param other defines the second operand
  4496. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4497. */
  4498. Quaternion.prototype.add = function (other) {
  4499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4500. };
  4501. /**
  4502. * Add a quaternion to the current one
  4503. * @param other defines the quaternion to add
  4504. * @returns the current quaternion
  4505. */
  4506. Quaternion.prototype.addInPlace = function (other) {
  4507. this.x += other.x;
  4508. this.y += other.y;
  4509. this.z += other.z;
  4510. this.w += other.w;
  4511. return this;
  4512. };
  4513. /**
  4514. * Subtract two quaternions
  4515. * @param other defines the second operand
  4516. * @returns a new quaternion as the subtraction result of the given one from the current one
  4517. */
  4518. Quaternion.prototype.subtract = function (other) {
  4519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4520. };
  4521. /**
  4522. * Multiplies the current quaternion by a scale factor
  4523. * @param value defines the scale factor
  4524. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4525. */
  4526. Quaternion.prototype.scale = function (value) {
  4527. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4528. };
  4529. /**
  4530. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4531. * @param scale defines the scale factor
  4532. * @param result defines the Quaternion object where to store the result
  4533. * @returns the unmodified current quaternion
  4534. */
  4535. Quaternion.prototype.scaleToRef = function (scale, result) {
  4536. result.x = this.x * scale;
  4537. result.y = this.y * scale;
  4538. result.z = this.z * scale;
  4539. result.w = this.w * scale;
  4540. return this;
  4541. };
  4542. /**
  4543. * Multiplies in place the current quaternion by a scale factor
  4544. * @param value defines the scale factor
  4545. * @returns the current modified quaternion
  4546. */
  4547. Quaternion.prototype.scaleInPlace = function (value) {
  4548. this.x *= value;
  4549. this.y *= value;
  4550. this.z *= value;
  4551. this.w *= value;
  4552. return this;
  4553. };
  4554. /**
  4555. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4556. * @param scale defines the scale factor
  4557. * @param result defines the Quaternion object where to store the result
  4558. * @returns the unmodified current quaternion
  4559. */
  4560. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4561. result.x += this.x * scale;
  4562. result.y += this.y * scale;
  4563. result.z += this.z * scale;
  4564. result.w += this.w * scale;
  4565. return this;
  4566. };
  4567. /**
  4568. * Multiplies two quaternions
  4569. * @param q1 defines the second operand
  4570. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4571. */
  4572. Quaternion.prototype.multiply = function (q1) {
  4573. var result = new Quaternion(0, 0, 0, 1.0);
  4574. this.multiplyToRef(q1, result);
  4575. return result;
  4576. };
  4577. /**
  4578. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4579. * @param q1 defines the second operand
  4580. * @param result defines the target quaternion
  4581. * @returns the current quaternion
  4582. */
  4583. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4584. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4585. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4586. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4587. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4588. result.copyFromFloats(x, y, z, w);
  4589. return this;
  4590. };
  4591. /**
  4592. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4593. * @param q1 defines the second operand
  4594. * @returns the currentupdated quaternion
  4595. */
  4596. Quaternion.prototype.multiplyInPlace = function (q1) {
  4597. this.multiplyToRef(q1, this);
  4598. return this;
  4599. };
  4600. /**
  4601. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4602. * @param ref defines the target quaternion
  4603. * @returns the current quaternion
  4604. */
  4605. Quaternion.prototype.conjugateToRef = function (ref) {
  4606. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4607. return this;
  4608. };
  4609. /**
  4610. * Conjugates in place (1-q) the current quaternion
  4611. * @returns the current updated quaternion
  4612. */
  4613. Quaternion.prototype.conjugateInPlace = function () {
  4614. this.x *= -1;
  4615. this.y *= -1;
  4616. this.z *= -1;
  4617. return this;
  4618. };
  4619. /**
  4620. * Conjugates in place (1-q) the current quaternion
  4621. * @returns a new quaternion
  4622. */
  4623. Quaternion.prototype.conjugate = function () {
  4624. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4625. return result;
  4626. };
  4627. /**
  4628. * Gets length of current quaternion
  4629. * @returns the quaternion length (float)
  4630. */
  4631. Quaternion.prototype.length = function () {
  4632. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4633. };
  4634. /**
  4635. * Normalize in place the current quaternion
  4636. * @returns the current updated quaternion
  4637. */
  4638. Quaternion.prototype.normalize = function () {
  4639. var length = 1.0 / this.length();
  4640. this.x *= length;
  4641. this.y *= length;
  4642. this.z *= length;
  4643. this.w *= length;
  4644. return this;
  4645. };
  4646. /**
  4647. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4648. * @param order is a reserved parameter and is ignore for now
  4649. * @returns a new Vector3 containing the Euler angles
  4650. */
  4651. Quaternion.prototype.toEulerAngles = function (order) {
  4652. if (order === void 0) { order = "YZX"; }
  4653. var result = Vector3.Zero();
  4654. this.toEulerAnglesToRef(result, order);
  4655. return result;
  4656. };
  4657. /**
  4658. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4659. * @param result defines the vector which will be filled with the Euler angles
  4660. * @param order is a reserved parameter and is ignore for now
  4661. * @returns the current unchanged quaternion
  4662. */
  4663. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4664. if (order === void 0) { order = "YZX"; }
  4665. var qz = this.z;
  4666. var qx = this.x;
  4667. var qy = this.y;
  4668. var qw = this.w;
  4669. var sqw = qw * qw;
  4670. var sqz = qz * qz;
  4671. var sqx = qx * qx;
  4672. var sqy = qy * qy;
  4673. var zAxisY = qy * qz - qx * qw;
  4674. var limit = .4999999;
  4675. if (zAxisY < -limit) {
  4676. result.y = 2 * Math.atan2(qy, qw);
  4677. result.x = Math.PI / 2;
  4678. result.z = 0;
  4679. }
  4680. else if (zAxisY > limit) {
  4681. result.y = 2 * Math.atan2(qy, qw);
  4682. result.x = -Math.PI / 2;
  4683. result.z = 0;
  4684. }
  4685. else {
  4686. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4687. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4688. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4689. }
  4690. return this;
  4691. };
  4692. /**
  4693. * Updates the given rotation matrix with the current quaternion values
  4694. * @param result defines the target matrix
  4695. * @returns the current unchanged quaternion
  4696. */
  4697. Quaternion.prototype.toRotationMatrix = function (result) {
  4698. var xx = this.x * this.x;
  4699. var yy = this.y * this.y;
  4700. var zz = this.z * this.z;
  4701. var xy = this.x * this.y;
  4702. var zw = this.z * this.w;
  4703. var zx = this.z * this.x;
  4704. var yw = this.y * this.w;
  4705. var yz = this.y * this.z;
  4706. var xw = this.x * this.w;
  4707. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4708. result.m[1] = 2.0 * (xy + zw);
  4709. result.m[2] = 2.0 * (zx - yw);
  4710. result.m[3] = 0;
  4711. result.m[4] = 2.0 * (xy - zw);
  4712. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4713. result.m[6] = 2.0 * (yz + xw);
  4714. result.m[7] = 0;
  4715. result.m[8] = 2.0 * (zx + yw);
  4716. result.m[9] = 2.0 * (yz - xw);
  4717. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4718. result.m[11] = 0;
  4719. result.m[12] = 0;
  4720. result.m[13] = 0;
  4721. result.m[14] = 0;
  4722. result.m[15] = 1.0;
  4723. result._markAsUpdated();
  4724. return this;
  4725. };
  4726. /**
  4727. * Updates the current quaternion from the given rotation matrix values
  4728. * @param matrix defines the source matrix
  4729. * @returns the current updated quaternion
  4730. */
  4731. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4732. Quaternion.FromRotationMatrixToRef(matrix, this);
  4733. return this;
  4734. };
  4735. // Statics
  4736. /**
  4737. * Creates a new quaternion from a rotation matrix
  4738. * @param matrix defines the source matrix
  4739. * @returns a new quaternion created from the given rotation matrix values
  4740. */
  4741. Quaternion.FromRotationMatrix = function (matrix) {
  4742. var result = new Quaternion();
  4743. Quaternion.FromRotationMatrixToRef(matrix, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Updates the given quaternion with the given rotation matrix values
  4748. * @param matrix defines the source matrix
  4749. * @param result defines the target quaternion
  4750. */
  4751. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4752. var data = matrix.m;
  4753. var m11 = data[0], m12 = data[4], m13 = data[8];
  4754. var m21 = data[1], m22 = data[5], m23 = data[9];
  4755. var m31 = data[2], m32 = data[6], m33 = data[10];
  4756. var trace = m11 + m22 + m33;
  4757. var s;
  4758. if (trace > 0) {
  4759. s = 0.5 / Math.sqrt(trace + 1.0);
  4760. result.w = 0.25 / s;
  4761. result.x = (m32 - m23) * s;
  4762. result.y = (m13 - m31) * s;
  4763. result.z = (m21 - m12) * s;
  4764. }
  4765. else if (m11 > m22 && m11 > m33) {
  4766. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4767. result.w = (m32 - m23) / s;
  4768. result.x = 0.25 * s;
  4769. result.y = (m12 + m21) / s;
  4770. result.z = (m13 + m31) / s;
  4771. }
  4772. else if (m22 > m33) {
  4773. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4774. result.w = (m13 - m31) / s;
  4775. result.x = (m12 + m21) / s;
  4776. result.y = 0.25 * s;
  4777. result.z = (m23 + m32) / s;
  4778. }
  4779. else {
  4780. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4781. result.w = (m21 - m12) / s;
  4782. result.x = (m13 + m31) / s;
  4783. result.y = (m23 + m32) / s;
  4784. result.z = 0.25 * s;
  4785. }
  4786. };
  4787. /**
  4788. * Returns the dot product (float) between the quaternions "left" and "right"
  4789. * @param left defines the left operand
  4790. * @param right defines the right operand
  4791. * @returns the dot product
  4792. */
  4793. Quaternion.Dot = function (left, right) {
  4794. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4795. };
  4796. /**
  4797. * Checks if the two quaternions are close to each other
  4798. * @param quat0 defines the first quaternion to check
  4799. * @param quat1 defines the second quaternion to check
  4800. * @returns true if the two quaternions are close to each other
  4801. */
  4802. Quaternion.AreClose = function (quat0, quat1) {
  4803. var dot = Quaternion.Dot(quat0, quat1);
  4804. return dot >= 0;
  4805. };
  4806. /**
  4807. * Creates an empty quaternion
  4808. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4809. */
  4810. Quaternion.Zero = function () {
  4811. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4812. };
  4813. /**
  4814. * Inverse a given quaternion
  4815. * @param q defines the source quaternion
  4816. * @returns a new quaternion as the inverted current quaternion
  4817. */
  4818. Quaternion.Inverse = function (q) {
  4819. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4820. };
  4821. /**
  4822. * Creates an identity quaternion
  4823. * @returns the identity quaternion
  4824. */
  4825. Quaternion.Identity = function () {
  4826. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4827. };
  4828. /**
  4829. * Gets a boolean indicating if the given quaternion is identity
  4830. * @param quaternion defines the quaternion to check
  4831. * @returns true if the quaternion is identity
  4832. */
  4833. Quaternion.IsIdentity = function (quaternion) {
  4834. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4835. };
  4836. /**
  4837. * Creates a quaternion from a rotation around an axis
  4838. * @param axis defines the axis to use
  4839. * @param angle defines the angle to use
  4840. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4841. */
  4842. Quaternion.RotationAxis = function (axis, angle) {
  4843. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4844. };
  4845. /**
  4846. * Creates a rotation around an axis and stores it into the given quaternion
  4847. * @param axis defines the axis to use
  4848. * @param angle defines the angle to use
  4849. * @param result defines the target quaternion
  4850. * @returns the target quaternion
  4851. */
  4852. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4853. var sin = Math.sin(angle / 2);
  4854. axis.normalize();
  4855. result.w = Math.cos(angle / 2);
  4856. result.x = axis.x * sin;
  4857. result.y = axis.y * sin;
  4858. result.z = axis.z * sin;
  4859. return result;
  4860. };
  4861. /**
  4862. * Creates a new quaternion from data stored into an array
  4863. * @param array defines the data source
  4864. * @param offset defines the offset in the source array where the data starts
  4865. * @returns a new quaternion
  4866. */
  4867. Quaternion.FromArray = function (array, offset) {
  4868. if (!offset) {
  4869. offset = 0;
  4870. }
  4871. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4872. };
  4873. /**
  4874. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4875. * @param yaw defines the rotation around Y axis
  4876. * @param pitch defines the rotation around X axis
  4877. * @param roll defines the rotation around Z axis
  4878. * @returns the new quaternion
  4879. */
  4880. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4881. var q = new Quaternion();
  4882. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4883. return q;
  4884. };
  4885. /**
  4886. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4887. * @param yaw defines the rotation around Y axis
  4888. * @param pitch defines the rotation around X axis
  4889. * @param roll defines the rotation around Z axis
  4890. * @param result defines the target quaternion
  4891. */
  4892. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4893. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4894. var halfRoll = roll * 0.5;
  4895. var halfPitch = pitch * 0.5;
  4896. var halfYaw = yaw * 0.5;
  4897. var sinRoll = Math.sin(halfRoll);
  4898. var cosRoll = Math.cos(halfRoll);
  4899. var sinPitch = Math.sin(halfPitch);
  4900. var cosPitch = Math.cos(halfPitch);
  4901. var sinYaw = Math.sin(halfYaw);
  4902. var cosYaw = Math.cos(halfYaw);
  4903. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4904. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4905. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4906. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4907. };
  4908. /**
  4909. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4910. * @param alpha defines the rotation around first axis
  4911. * @param beta defines the rotation around second axis
  4912. * @param gamma defines the rotation around third axis
  4913. * @returns the new quaternion
  4914. */
  4915. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4916. var result = new Quaternion();
  4917. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4918. return result;
  4919. };
  4920. /**
  4921. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4922. * @param alpha defines the rotation around first axis
  4923. * @param beta defines the rotation around second axis
  4924. * @param gamma defines the rotation around third axis
  4925. * @param result defines the target quaternion
  4926. */
  4927. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4928. // Produces a quaternion from Euler angles in the z-x-z orientation
  4929. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4930. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4931. var halfBeta = beta * 0.5;
  4932. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4933. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4934. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4935. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4936. };
  4937. /**
  4938. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4939. * @param axis1 defines the first axis
  4940. * @param axis2 defines the second axis
  4941. * @param axis3 defines the third axis
  4942. * @returns the new quaternion
  4943. */
  4944. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4945. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4946. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4947. return quat;
  4948. };
  4949. /**
  4950. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4951. * @param axis1 defines the first axis
  4952. * @param axis2 defines the second axis
  4953. * @param axis3 defines the third axis
  4954. * @param ref defines the target quaternion
  4955. */
  4956. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4957. var rotMat = MathTmp.Matrix[0];
  4958. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4959. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4960. };
  4961. /**
  4962. * Interpolates between two quaternions
  4963. * @param left defines first quaternion
  4964. * @param right defines second quaternion
  4965. * @param amount defines the gradient to use
  4966. * @returns the new interpolated quaternion
  4967. */
  4968. Quaternion.Slerp = function (left, right, amount) {
  4969. var result = Quaternion.Identity();
  4970. Quaternion.SlerpToRef(left, right, amount, result);
  4971. return result;
  4972. };
  4973. /**
  4974. * Interpolates between two quaternions and stores it into a target quaternion
  4975. * @param left defines first quaternion
  4976. * @param right defines second quaternion
  4977. * @param amount defines the gradient to use
  4978. * @param result defines the target quaternion
  4979. */
  4980. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4981. var num2;
  4982. var num3;
  4983. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4984. var flag = false;
  4985. if (num4 < 0) {
  4986. flag = true;
  4987. num4 = -num4;
  4988. }
  4989. if (num4 > 0.999999) {
  4990. num3 = 1 - amount;
  4991. num2 = flag ? -amount : amount;
  4992. }
  4993. else {
  4994. var num5 = Math.acos(num4);
  4995. var num6 = (1.0 / Math.sin(num5));
  4996. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4997. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4998. }
  4999. result.x = (num3 * left.x) + (num2 * right.x);
  5000. result.y = (num3 * left.y) + (num2 * right.y);
  5001. result.z = (num3 * left.z) + (num2 * right.z);
  5002. result.w = (num3 * left.w) + (num2 * right.w);
  5003. };
  5004. /**
  5005. * Interpolate between two quaternions using Hermite interpolation
  5006. * @param value1 defines first quaternion
  5007. * @param tangent1 defines the incoming tangent
  5008. * @param value2 defines second quaternion
  5009. * @param tangent2 defines the outgoing tangent
  5010. * @param amount defines the target quaternion
  5011. * @returns the new interpolated quaternion
  5012. */
  5013. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5014. var squared = amount * amount;
  5015. var cubed = amount * squared;
  5016. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5017. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5018. var part3 = (cubed - (2.0 * squared)) + amount;
  5019. var part4 = cubed - squared;
  5020. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5021. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5022. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5023. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5024. return new Quaternion(x, y, z, w);
  5025. };
  5026. return Quaternion;
  5027. }());
  5028. BABYLON.Quaternion = Quaternion;
  5029. /**
  5030. * Class used to store matrix data (4x4)
  5031. */
  5032. var Matrix = /** @class */ (function () {
  5033. /**
  5034. * Creates an empty matrix (filled with zeros)
  5035. */
  5036. function Matrix() {
  5037. this._isIdentity = false;
  5038. this._isIdentityDirty = true;
  5039. /**
  5040. * Gets or sets the internal data of the matrix
  5041. */
  5042. this.m = new Float32Array(16);
  5043. this._markAsUpdated();
  5044. }
  5045. /** @hidden */
  5046. Matrix.prototype._markAsUpdated = function () {
  5047. this.updateFlag = Matrix._updateFlagSeed++;
  5048. this._isIdentityDirty = true;
  5049. };
  5050. // Properties
  5051. /**
  5052. * Check if the current matrix is indentity
  5053. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5054. * @returns true is the matrix is the identity matrix
  5055. */
  5056. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5057. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5058. if (this._isIdentityDirty) {
  5059. this._isIdentityDirty = false;
  5060. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5061. this._isIdentity = false;
  5062. }
  5063. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5064. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5065. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5066. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5067. this._isIdentity = false;
  5068. }
  5069. else {
  5070. this._isIdentity = true;
  5071. }
  5072. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5073. this._isIdentity = false;
  5074. }
  5075. }
  5076. return this._isIdentity;
  5077. };
  5078. /**
  5079. * Gets the determinant of the matrix
  5080. * @returns the matrix determinant
  5081. */
  5082. Matrix.prototype.determinant = function () {
  5083. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5084. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5085. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5086. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5087. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5088. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5089. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5090. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5091. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5092. };
  5093. // Methods
  5094. /**
  5095. * Returns the matrix as a Float32Array
  5096. * @returns the matrix underlying array
  5097. */
  5098. Matrix.prototype.toArray = function () {
  5099. return this.m;
  5100. };
  5101. /**
  5102. * Returns the matrix as a Float32Array
  5103. * @returns the matrix underlying array.
  5104. */
  5105. Matrix.prototype.asArray = function () {
  5106. return this.toArray();
  5107. };
  5108. /**
  5109. * Inverts the current matrix in place
  5110. * @returns the current inverted matrix
  5111. */
  5112. Matrix.prototype.invert = function () {
  5113. this.invertToRef(this);
  5114. return this;
  5115. };
  5116. /**
  5117. * Sets all the matrix elements to zero
  5118. * @returns the current matrix
  5119. */
  5120. Matrix.prototype.reset = function () {
  5121. for (var index = 0; index < 16; index++) {
  5122. this.m[index] = 0.0;
  5123. }
  5124. this._markAsUpdated();
  5125. return this;
  5126. };
  5127. /**
  5128. * Adds the current matrix with a second one
  5129. * @param other defines the matrix to add
  5130. * @returns a new matrix as the addition of the current matrix and the given one
  5131. */
  5132. Matrix.prototype.add = function (other) {
  5133. var result = new Matrix();
  5134. this.addToRef(other, result);
  5135. return result;
  5136. };
  5137. /**
  5138. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5139. * @param other defines the matrix to add
  5140. * @param result defines the target matrix
  5141. * @returns the current matrix
  5142. */
  5143. Matrix.prototype.addToRef = function (other, result) {
  5144. for (var index = 0; index < 16; index++) {
  5145. result.m[index] = this.m[index] + other.m[index];
  5146. }
  5147. result._markAsUpdated();
  5148. return this;
  5149. };
  5150. /**
  5151. * Adds in place the given matrix to the current matrix
  5152. * @param other defines the second operand
  5153. * @returns the current updated matrix
  5154. */
  5155. Matrix.prototype.addToSelf = function (other) {
  5156. for (var index = 0; index < 16; index++) {
  5157. this.m[index] += other.m[index];
  5158. }
  5159. this._markAsUpdated();
  5160. return this;
  5161. };
  5162. /**
  5163. * Sets the given matrix to the current inverted Matrix
  5164. * @param other defines the target matrix
  5165. * @returns the unmodified current matrix
  5166. */
  5167. Matrix.prototype.invertToRef = function (other) {
  5168. var l1 = this.m[0];
  5169. var l2 = this.m[1];
  5170. var l3 = this.m[2];
  5171. var l4 = this.m[3];
  5172. var l5 = this.m[4];
  5173. var l6 = this.m[5];
  5174. var l7 = this.m[6];
  5175. var l8 = this.m[7];
  5176. var l9 = this.m[8];
  5177. var l10 = this.m[9];
  5178. var l11 = this.m[10];
  5179. var l12 = this.m[11];
  5180. var l13 = this.m[12];
  5181. var l14 = this.m[13];
  5182. var l15 = this.m[14];
  5183. var l16 = this.m[15];
  5184. var l17 = (l11 * l16) - (l12 * l15);
  5185. var l18 = (l10 * l16) - (l12 * l14);
  5186. var l19 = (l10 * l15) - (l11 * l14);
  5187. var l20 = (l9 * l16) - (l12 * l13);
  5188. var l21 = (l9 * l15) - (l11 * l13);
  5189. var l22 = (l9 * l14) - (l10 * l13);
  5190. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5191. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5192. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5193. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5194. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5195. var l28 = (l7 * l16) - (l8 * l15);
  5196. var l29 = (l6 * l16) - (l8 * l14);
  5197. var l30 = (l6 * l15) - (l7 * l14);
  5198. var l31 = (l5 * l16) - (l8 * l13);
  5199. var l32 = (l5 * l15) - (l7 * l13);
  5200. var l33 = (l5 * l14) - (l6 * l13);
  5201. var l34 = (l7 * l12) - (l8 * l11);
  5202. var l35 = (l6 * l12) - (l8 * l10);
  5203. var l36 = (l6 * l11) - (l7 * l10);
  5204. var l37 = (l5 * l12) - (l8 * l9);
  5205. var l38 = (l5 * l11) - (l7 * l9);
  5206. var l39 = (l5 * l10) - (l6 * l9);
  5207. other.m[0] = l23 * l27;
  5208. other.m[4] = l24 * l27;
  5209. other.m[8] = l25 * l27;
  5210. other.m[12] = l26 * l27;
  5211. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5212. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5213. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5214. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5215. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5216. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5217. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5218. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5219. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5220. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5221. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5222. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5223. other._markAsUpdated();
  5224. return this;
  5225. };
  5226. /**
  5227. * Inserts the translation vector (using 3 floats) in the current matrix
  5228. * @param x defines the 1st component of the translation
  5229. * @param y defines the 2nd component of the translation
  5230. * @param z defines the 3rd component of the translation
  5231. * @returns the current updated matrix
  5232. */
  5233. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5234. this.m[12] = x;
  5235. this.m[13] = y;
  5236. this.m[14] = z;
  5237. this._markAsUpdated();
  5238. return this;
  5239. };
  5240. /**
  5241. * Inserts the translation vector in the current matrix
  5242. * @param vector3 defines the translation to insert
  5243. * @returns the current updated matrix
  5244. */
  5245. Matrix.prototype.setTranslation = function (vector3) {
  5246. this.m[12] = vector3.x;
  5247. this.m[13] = vector3.y;
  5248. this.m[14] = vector3.z;
  5249. this._markAsUpdated();
  5250. return this;
  5251. };
  5252. /**
  5253. * Gets the translation value of the current matrix
  5254. * @returns a new Vector3 as the extracted translation from the matrix
  5255. */
  5256. Matrix.prototype.getTranslation = function () {
  5257. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5258. };
  5259. /**
  5260. * Fill a Vector3 with the extracted translation from the matrix
  5261. * @param result defines the Vector3 where to store the translation
  5262. * @returns the current matrix
  5263. */
  5264. Matrix.prototype.getTranslationToRef = function (result) {
  5265. result.x = this.m[12];
  5266. result.y = this.m[13];
  5267. result.z = this.m[14];
  5268. return this;
  5269. };
  5270. /**
  5271. * Remove rotation and scaling part from the matrix
  5272. * @returns the updated matrix
  5273. */
  5274. Matrix.prototype.removeRotationAndScaling = function () {
  5275. this.setRowFromFloats(0, 1, 0, 0, 0);
  5276. this.setRowFromFloats(1, 0, 1, 0, 0);
  5277. this.setRowFromFloats(2, 0, 0, 1, 0);
  5278. return this;
  5279. };
  5280. /**
  5281. * Multiply two matrices
  5282. * @param other defines the second operand
  5283. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5284. */
  5285. Matrix.prototype.multiply = function (other) {
  5286. var result = new Matrix();
  5287. this.multiplyToRef(other, result);
  5288. return result;
  5289. };
  5290. /**
  5291. * Copy the current matrix from the given one
  5292. * @param other defines the source matrix
  5293. * @returns the current updated matrix
  5294. */
  5295. Matrix.prototype.copyFrom = function (other) {
  5296. for (var index = 0; index < 16; index++) {
  5297. this.m[index] = other.m[index];
  5298. }
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Populates the given array from the starting index with the current matrix values
  5304. * @param array defines the target array
  5305. * @param offset defines the offset in the target array where to start storing values
  5306. * @returns the current matrix
  5307. */
  5308. Matrix.prototype.copyToArray = function (array, offset) {
  5309. if (offset === void 0) { offset = 0; }
  5310. for (var index = 0; index < 16; index++) {
  5311. array[offset + index] = this.m[index];
  5312. }
  5313. return this;
  5314. };
  5315. /**
  5316. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5317. * @param other defines the second operand
  5318. * @param result defines the matrix where to store the multiplication
  5319. * @returns the current matrix
  5320. */
  5321. Matrix.prototype.multiplyToRef = function (other, result) {
  5322. this.multiplyToArray(other, result.m, 0);
  5323. result._markAsUpdated();
  5324. return this;
  5325. };
  5326. /**
  5327. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5328. * @param other defines the second operand
  5329. * @param result defines the array where to store the multiplication
  5330. * @param offset defines the offset in the target array where to start storing values
  5331. * @returns the current matrix
  5332. */
  5333. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5334. var tm0 = this.m[0];
  5335. var tm1 = this.m[1];
  5336. var tm2 = this.m[2];
  5337. var tm3 = this.m[3];
  5338. var tm4 = this.m[4];
  5339. var tm5 = this.m[5];
  5340. var tm6 = this.m[6];
  5341. var tm7 = this.m[7];
  5342. var tm8 = this.m[8];
  5343. var tm9 = this.m[9];
  5344. var tm10 = this.m[10];
  5345. var tm11 = this.m[11];
  5346. var tm12 = this.m[12];
  5347. var tm13 = this.m[13];
  5348. var tm14 = this.m[14];
  5349. var tm15 = this.m[15];
  5350. var om0 = other.m[0];
  5351. var om1 = other.m[1];
  5352. var om2 = other.m[2];
  5353. var om3 = other.m[3];
  5354. var om4 = other.m[4];
  5355. var om5 = other.m[5];
  5356. var om6 = other.m[6];
  5357. var om7 = other.m[7];
  5358. var om8 = other.m[8];
  5359. var om9 = other.m[9];
  5360. var om10 = other.m[10];
  5361. var om11 = other.m[11];
  5362. var om12 = other.m[12];
  5363. var om13 = other.m[13];
  5364. var om14 = other.m[14];
  5365. var om15 = other.m[15];
  5366. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5367. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5368. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5369. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5370. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5371. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5372. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5373. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5374. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5375. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5376. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5377. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5378. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5379. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5380. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5381. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5382. return this;
  5383. };
  5384. /**
  5385. * Check equality between this matrix and a second one
  5386. * @param value defines the second matrix to compare
  5387. * @returns true is the current matrix and the given one values are strictly equal
  5388. */
  5389. Matrix.prototype.equals = function (value) {
  5390. return value &&
  5391. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5392. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5393. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5394. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5395. };
  5396. /**
  5397. * Clone the current matrix
  5398. * @returns a new matrix from the current matrix
  5399. */
  5400. Matrix.prototype.clone = function () {
  5401. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5402. };
  5403. /**
  5404. * Returns the name of the current matrix class
  5405. * @returns the string "Matrix"
  5406. */
  5407. Matrix.prototype.getClassName = function () {
  5408. return "Matrix";
  5409. };
  5410. /**
  5411. * Gets the hash code of the current matrix
  5412. * @returns the hash code
  5413. */
  5414. Matrix.prototype.getHashCode = function () {
  5415. var hash = this.m[0] || 0;
  5416. for (var i = 1; i < 16; i++) {
  5417. hash = (hash * 397) ^ (this.m[i] || 0);
  5418. }
  5419. return hash;
  5420. };
  5421. /**
  5422. * Decomposes the current Matrix into a translation, rotation and scaling components
  5423. * @param scale defines the scale vector3 given as a reference to update
  5424. * @param rotation defines the rotation quaternion given as a reference to update
  5425. * @param translation defines the translation vector3 given as a reference to update
  5426. * @returns true if operation was successful
  5427. */
  5428. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5429. if (translation) {
  5430. translation.x = this.m[12];
  5431. translation.y = this.m[13];
  5432. translation.z = this.m[14];
  5433. }
  5434. scale = scale || MathTmp.Vector3[0];
  5435. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5436. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5437. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5438. if (this.determinant() <= 0) {
  5439. scale.y *= -1;
  5440. }
  5441. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5442. if (rotation) {
  5443. rotation.x = 0;
  5444. rotation.y = 0;
  5445. rotation.z = 0;
  5446. rotation.w = 1;
  5447. }
  5448. return false;
  5449. }
  5450. if (rotation) {
  5451. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5452. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5453. }
  5454. return true;
  5455. };
  5456. /**
  5457. * Gets specific row of the matrix
  5458. * @param index defines the number of the row to get
  5459. * @returns the index-th row of the current matrix as a new Vector4
  5460. */
  5461. Matrix.prototype.getRow = function (index) {
  5462. if (index < 0 || index > 3) {
  5463. return null;
  5464. }
  5465. var i = index * 4;
  5466. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5467. };
  5468. /**
  5469. * Sets the index-th row of the current matrix to the vector4 values
  5470. * @param index defines the number of the row to set
  5471. * @param row defines the target vector4
  5472. * @returns the updated current matrix
  5473. */
  5474. Matrix.prototype.setRow = function (index, row) {
  5475. if (index < 0 || index > 3) {
  5476. return this;
  5477. }
  5478. var i = index * 4;
  5479. this.m[i + 0] = row.x;
  5480. this.m[i + 1] = row.y;
  5481. this.m[i + 2] = row.z;
  5482. this.m[i + 3] = row.w;
  5483. this._markAsUpdated();
  5484. return this;
  5485. };
  5486. /**
  5487. * Compute the transpose of the matrix
  5488. * @returns the new transposed matrix
  5489. */
  5490. Matrix.prototype.transpose = function () {
  5491. return Matrix.Transpose(this);
  5492. };
  5493. /**
  5494. * Compute the transpose of the matrix and store it in a given matrix
  5495. * @param result defines the target matrix
  5496. * @returns the current matrix
  5497. */
  5498. Matrix.prototype.transposeToRef = function (result) {
  5499. Matrix.TransposeToRef(this, result);
  5500. return this;
  5501. };
  5502. /**
  5503. * Sets the index-th row of the current matrix with the given 4 x float values
  5504. * @param index defines the row index
  5505. * @param x defines the x component to set
  5506. * @param y defines the y component to set
  5507. * @param z defines the z component to set
  5508. * @param w defines the w component to set
  5509. * @returns the updated current matrix
  5510. */
  5511. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5512. if (index < 0 || index > 3) {
  5513. return this;
  5514. }
  5515. var i = index * 4;
  5516. this.m[i + 0] = x;
  5517. this.m[i + 1] = y;
  5518. this.m[i + 2] = z;
  5519. this.m[i + 3] = w;
  5520. this._markAsUpdated();
  5521. return this;
  5522. };
  5523. /**
  5524. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5525. * @param scale defines the scale factor
  5526. * @returns a new matrix
  5527. */
  5528. Matrix.prototype.scale = function (scale) {
  5529. var result = new Matrix();
  5530. this.scaleToRef(scale, result);
  5531. return result;
  5532. };
  5533. /**
  5534. * Scale the current matrix values by a factor to a given result matrix
  5535. * @param scale defines the scale factor
  5536. * @param result defines the matrix to store the result
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.scaleToRef = function (scale, result) {
  5540. for (var index = 0; index < 16; index++) {
  5541. result.m[index] = this.m[index] * scale;
  5542. }
  5543. result._markAsUpdated();
  5544. return this;
  5545. };
  5546. /**
  5547. * Scale the current matrix values by a factor and add the result to a given matrix
  5548. * @param scale defines the scale factor
  5549. * @param result defines the Matrix to store the result
  5550. * @returns the current matrix
  5551. */
  5552. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5553. for (var index = 0; index < 16; index++) {
  5554. result.m[index] += this.m[index] * scale;
  5555. }
  5556. result._markAsUpdated();
  5557. return this;
  5558. };
  5559. /**
  5560. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5561. * @param ref matrix to store the result
  5562. */
  5563. Matrix.prototype.toNormalMatrix = function (ref) {
  5564. this.invertToRef(ref);
  5565. ref.transpose();
  5566. var m = ref.m;
  5567. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5568. };
  5569. /**
  5570. * Gets only rotation part of the current matrix
  5571. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5572. */
  5573. Matrix.prototype.getRotationMatrix = function () {
  5574. var result = Matrix.Identity();
  5575. this.getRotationMatrixToRef(result);
  5576. return result;
  5577. };
  5578. /**
  5579. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5580. * @param result defines the target matrix to store data to
  5581. * @returns the current matrix
  5582. */
  5583. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5584. var m = this.m;
  5585. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5586. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5587. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5588. if (this.determinant() <= 0) {
  5589. sy *= -1;
  5590. }
  5591. if (sx === 0 || sy === 0 || sz === 0) {
  5592. Matrix.IdentityToRef(result);
  5593. }
  5594. else {
  5595. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5596. }
  5597. return this;
  5598. };
  5599. // Statics
  5600. /**
  5601. * Creates a matrix from an array
  5602. * @param array defines the source array
  5603. * @param offset defines an offset in the source array
  5604. * @returns a new Matrix set from the starting index of the given array
  5605. */
  5606. Matrix.FromArray = function (array, offset) {
  5607. var result = new Matrix();
  5608. if (!offset) {
  5609. offset = 0;
  5610. }
  5611. Matrix.FromArrayToRef(array, offset, result);
  5612. return result;
  5613. };
  5614. /**
  5615. * Copy the content of an array into a given matrix
  5616. * @param array defines the source array
  5617. * @param offset defines an offset in the source array
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromArrayToRef = function (array, offset, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = array[index + offset];
  5623. }
  5624. result._markAsUpdated();
  5625. };
  5626. /**
  5627. * Stores an array into a matrix after having multiplied each component by a given factor
  5628. * @param array defines the source array
  5629. * @param offset defines the offset in the source array
  5630. * @param scale defines the scaling factor
  5631. * @param result defines the target matrix
  5632. */
  5633. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5634. for (var index = 0; index < 16; index++) {
  5635. result.m[index] = array[index + offset] * scale;
  5636. }
  5637. result._markAsUpdated();
  5638. };
  5639. /**
  5640. * Stores a list of values (16) inside a given matrix
  5641. * @param initialM11 defines 1st value of 1st row
  5642. * @param initialM12 defines 2nd value of 1st row
  5643. * @param initialM13 defines 3rd value of 1st row
  5644. * @param initialM14 defines 4th value of 1st row
  5645. * @param initialM21 defines 1st value of 2nd row
  5646. * @param initialM22 defines 2nd value of 2nd row
  5647. * @param initialM23 defines 3rd value of 2nd row
  5648. * @param initialM24 defines 4th value of 2nd row
  5649. * @param initialM31 defines 1st value of 3rd row
  5650. * @param initialM32 defines 2nd value of 3rd row
  5651. * @param initialM33 defines 3rd value of 3rd row
  5652. * @param initialM34 defines 4th value of 3rd row
  5653. * @param initialM41 defines 1st value of 4th row
  5654. * @param initialM42 defines 2nd value of 4th row
  5655. * @param initialM43 defines 3rd value of 4th row
  5656. * @param initialM44 defines 4th value of 4th row
  5657. * @param result defines the target matrix
  5658. */
  5659. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5660. result.m[0] = initialM11;
  5661. result.m[1] = initialM12;
  5662. result.m[2] = initialM13;
  5663. result.m[3] = initialM14;
  5664. result.m[4] = initialM21;
  5665. result.m[5] = initialM22;
  5666. result.m[6] = initialM23;
  5667. result.m[7] = initialM24;
  5668. result.m[8] = initialM31;
  5669. result.m[9] = initialM32;
  5670. result.m[10] = initialM33;
  5671. result.m[11] = initialM34;
  5672. result.m[12] = initialM41;
  5673. result.m[13] = initialM42;
  5674. result.m[14] = initialM43;
  5675. result.m[15] = initialM44;
  5676. result._markAsUpdated();
  5677. };
  5678. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5679. /**
  5680. * Gets an identity matrix that must not be updated
  5681. */
  5682. get: function () {
  5683. return Matrix._identityReadOnly;
  5684. },
  5685. enumerable: true,
  5686. configurable: true
  5687. });
  5688. /**
  5689. * Creates new matrix from a list of values (16)
  5690. * @param initialM11 defines 1st value of 1st row
  5691. * @param initialM12 defines 2nd value of 1st row
  5692. * @param initialM13 defines 3rd value of 1st row
  5693. * @param initialM14 defines 4th value of 1st row
  5694. * @param initialM21 defines 1st value of 2nd row
  5695. * @param initialM22 defines 2nd value of 2nd row
  5696. * @param initialM23 defines 3rd value of 2nd row
  5697. * @param initialM24 defines 4th value of 2nd row
  5698. * @param initialM31 defines 1st value of 3rd row
  5699. * @param initialM32 defines 2nd value of 3rd row
  5700. * @param initialM33 defines 3rd value of 3rd row
  5701. * @param initialM34 defines 4th value of 3rd row
  5702. * @param initialM41 defines 1st value of 4th row
  5703. * @param initialM42 defines 2nd value of 4th row
  5704. * @param initialM43 defines 3rd value of 4th row
  5705. * @param initialM44 defines 4th value of 4th row
  5706. * @returns the new matrix
  5707. */
  5708. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5709. var result = new Matrix();
  5710. result.m[0] = initialM11;
  5711. result.m[1] = initialM12;
  5712. result.m[2] = initialM13;
  5713. result.m[3] = initialM14;
  5714. result.m[4] = initialM21;
  5715. result.m[5] = initialM22;
  5716. result.m[6] = initialM23;
  5717. result.m[7] = initialM24;
  5718. result.m[8] = initialM31;
  5719. result.m[9] = initialM32;
  5720. result.m[10] = initialM33;
  5721. result.m[11] = initialM34;
  5722. result.m[12] = initialM41;
  5723. result.m[13] = initialM42;
  5724. result.m[14] = initialM43;
  5725. result.m[15] = initialM44;
  5726. return result;
  5727. };
  5728. /**
  5729. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5730. * @param scale defines the scale vector3
  5731. * @param rotation defines the rotation quaternion
  5732. * @param translation defines the translation vector3
  5733. * @returns a new matrix
  5734. */
  5735. Matrix.Compose = function (scale, rotation, translation) {
  5736. var result = Matrix.Identity();
  5737. Matrix.ComposeToRef(scale, rotation, translation, result);
  5738. return result;
  5739. };
  5740. /**
  5741. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5742. * @param scale defines the scale vector3
  5743. * @param rotation defines the rotation quaternion
  5744. * @param translation defines the translation vector3
  5745. * @param result defines the target matrix
  5746. */
  5747. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5748. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5749. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5750. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5751. result.setTranslation(translation);
  5752. };
  5753. /**
  5754. * Creates a new identity matrix
  5755. * @returns a new identity matrix
  5756. */
  5757. Matrix.Identity = function () {
  5758. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5759. };
  5760. /**
  5761. * Creates a new identity matrix and stores the result in a given matrix
  5762. * @param result defines the target matrix
  5763. */
  5764. Matrix.IdentityToRef = function (result) {
  5765. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5766. };
  5767. /**
  5768. * Creates a new zero matrix
  5769. * @returns a new zero matrix
  5770. */
  5771. Matrix.Zero = function () {
  5772. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5773. };
  5774. /**
  5775. * Creates a new rotation matrix for "angle" radians around the X axis
  5776. * @param angle defines the angle (in radians) to use
  5777. * @return the new matrix
  5778. */
  5779. Matrix.RotationX = function (angle) {
  5780. var result = new Matrix();
  5781. Matrix.RotationXToRef(angle, result);
  5782. return result;
  5783. };
  5784. /**
  5785. * Creates a new matrix as the invert of a given matrix
  5786. * @param source defines the source matrix
  5787. * @returns the new matrix
  5788. */
  5789. Matrix.Invert = function (source) {
  5790. var result = new Matrix();
  5791. source.invertToRef(result);
  5792. return result;
  5793. };
  5794. /**
  5795. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5796. * @param angle defines the angle (in radians) to use
  5797. * @param result defines the target matrix
  5798. */
  5799. Matrix.RotationXToRef = function (angle, result) {
  5800. var s = Math.sin(angle);
  5801. var c = Math.cos(angle);
  5802. result.m[0] = 1.0;
  5803. result.m[15] = 1.0;
  5804. result.m[5] = c;
  5805. result.m[10] = c;
  5806. result.m[9] = -s;
  5807. result.m[6] = s;
  5808. result.m[1] = 0.0;
  5809. result.m[2] = 0.0;
  5810. result.m[3] = 0.0;
  5811. result.m[4] = 0.0;
  5812. result.m[7] = 0.0;
  5813. result.m[8] = 0.0;
  5814. result.m[11] = 0.0;
  5815. result.m[12] = 0.0;
  5816. result.m[13] = 0.0;
  5817. result.m[14] = 0.0;
  5818. result._markAsUpdated();
  5819. };
  5820. /**
  5821. * Creates a new rotation matrix for "angle" radians around the Y axis
  5822. * @param angle defines the angle (in radians) to use
  5823. * @return the new matrix
  5824. */
  5825. Matrix.RotationY = function (angle) {
  5826. var result = new Matrix();
  5827. Matrix.RotationYToRef(angle, result);
  5828. return result;
  5829. };
  5830. /**
  5831. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5832. * @param angle defines the angle (in radians) to use
  5833. * @param result defines the target matrix
  5834. */
  5835. Matrix.RotationYToRef = function (angle, result) {
  5836. var s = Math.sin(angle);
  5837. var c = Math.cos(angle);
  5838. result.m[5] = 1.0;
  5839. result.m[15] = 1.0;
  5840. result.m[0] = c;
  5841. result.m[2] = -s;
  5842. result.m[8] = s;
  5843. result.m[10] = c;
  5844. result.m[1] = 0.0;
  5845. result.m[3] = 0.0;
  5846. result.m[4] = 0.0;
  5847. result.m[6] = 0.0;
  5848. result.m[7] = 0.0;
  5849. result.m[9] = 0.0;
  5850. result.m[11] = 0.0;
  5851. result.m[12] = 0.0;
  5852. result.m[13] = 0.0;
  5853. result.m[14] = 0.0;
  5854. result._markAsUpdated();
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the Z axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationZ = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationZToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5868. * @param angle defines the angle (in radians) to use
  5869. * @param result defines the target matrix
  5870. */
  5871. Matrix.RotationZToRef = function (angle, result) {
  5872. var s = Math.sin(angle);
  5873. var c = Math.cos(angle);
  5874. result.m[10] = 1.0;
  5875. result.m[15] = 1.0;
  5876. result.m[0] = c;
  5877. result.m[1] = s;
  5878. result.m[4] = -s;
  5879. result.m[5] = c;
  5880. result.m[2] = 0.0;
  5881. result.m[3] = 0.0;
  5882. result.m[6] = 0.0;
  5883. result.m[7] = 0.0;
  5884. result.m[8] = 0.0;
  5885. result.m[9] = 0.0;
  5886. result.m[11] = 0.0;
  5887. result.m[12] = 0.0;
  5888. result.m[13] = 0.0;
  5889. result.m[14] = 0.0;
  5890. result._markAsUpdated();
  5891. };
  5892. /**
  5893. * Creates a new rotation matrix for "angle" radians around the given axis
  5894. * @param axis defines the axis to use
  5895. * @param angle defines the angle (in radians) to use
  5896. * @return the new matrix
  5897. */
  5898. Matrix.RotationAxis = function (axis, angle) {
  5899. var result = Matrix.Zero();
  5900. Matrix.RotationAxisToRef(axis, angle, result);
  5901. return result;
  5902. };
  5903. /**
  5904. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5905. * @param axis defines the axis to use
  5906. * @param angle defines the angle (in radians) to use
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5910. var s = Math.sin(-angle);
  5911. var c = Math.cos(-angle);
  5912. var c1 = 1 - c;
  5913. axis.normalize();
  5914. result.m[0] = (axis.x * axis.x) * c1 + c;
  5915. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5916. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5917. result.m[3] = 0.0;
  5918. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5919. result.m[5] = (axis.y * axis.y) * c1 + c;
  5920. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5921. result.m[7] = 0.0;
  5922. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5923. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5924. result.m[10] = (axis.z * axis.z) * c1 + c;
  5925. result.m[11] = 0.0;
  5926. result.m[15] = 1.0;
  5927. result._markAsUpdated();
  5928. };
  5929. /**
  5930. * Creates a rotation matrix
  5931. * @param yaw defines the yaw angle in radians (Y axis)
  5932. * @param pitch defines the pitch angle in radians (X axis)
  5933. * @param roll defines the roll angle in radians (X axis)
  5934. * @returns the new rotation matrix
  5935. */
  5936. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5937. var result = new Matrix();
  5938. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5939. return result;
  5940. };
  5941. /**
  5942. * Creates a rotation matrix and stores it in a given matrix
  5943. * @param yaw defines the yaw angle in radians (Y axis)
  5944. * @param pitch defines the pitch angle in radians (X axis)
  5945. * @param roll defines the roll angle in radians (X axis)
  5946. * @param result defines the target matrix
  5947. */
  5948. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5949. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5950. this._tempQuaternion.toRotationMatrix(result);
  5951. };
  5952. /**
  5953. * Creates a scaling matrix
  5954. * @param x defines the scale factor on X axis
  5955. * @param y defines the scale factor on Y axis
  5956. * @param z defines the scale factor on Z axis
  5957. * @returns the new matrix
  5958. */
  5959. Matrix.Scaling = function (x, y, z) {
  5960. var result = Matrix.Zero();
  5961. Matrix.ScalingToRef(x, y, z, result);
  5962. return result;
  5963. };
  5964. /**
  5965. * Creates a scaling matrix and stores it in a given matrix
  5966. * @param x defines the scale factor on X axis
  5967. * @param y defines the scale factor on Y axis
  5968. * @param z defines the scale factor on Z axis
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.ScalingToRef = function (x, y, z, result) {
  5972. result.m[0] = x;
  5973. result.m[1] = 0.0;
  5974. result.m[2] = 0.0;
  5975. result.m[3] = 0.0;
  5976. result.m[4] = 0.0;
  5977. result.m[5] = y;
  5978. result.m[6] = 0.0;
  5979. result.m[7] = 0.0;
  5980. result.m[8] = 0.0;
  5981. result.m[9] = 0.0;
  5982. result.m[10] = z;
  5983. result.m[11] = 0.0;
  5984. result.m[12] = 0.0;
  5985. result.m[13] = 0.0;
  5986. result.m[14] = 0.0;
  5987. result.m[15] = 1.0;
  5988. result._markAsUpdated();
  5989. };
  5990. /**
  5991. * Creates a translation matrix
  5992. * @param x defines the translation on X axis
  5993. * @param y defines the translation on Y axis
  5994. * @param z defines the translationon Z axis
  5995. * @returns the new matrix
  5996. */
  5997. Matrix.Translation = function (x, y, z) {
  5998. var result = Matrix.Identity();
  5999. Matrix.TranslationToRef(x, y, z, result);
  6000. return result;
  6001. };
  6002. /**
  6003. * Creates a translation matrix and stores it in a given matrix
  6004. * @param x defines the translation on X axis
  6005. * @param y defines the translation on Y axis
  6006. * @param z defines the translationon Z axis
  6007. * @param result defines the target matrix
  6008. */
  6009. Matrix.TranslationToRef = function (x, y, z, result) {
  6010. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6011. };
  6012. /**
  6013. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6014. * @param startValue defines the start value
  6015. * @param endValue defines the end value
  6016. * @param gradient defines the gradient factor
  6017. * @returns the new matrix
  6018. */
  6019. Matrix.Lerp = function (startValue, endValue, gradient) {
  6020. var result = Matrix.Zero();
  6021. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6022. return result;
  6023. };
  6024. /**
  6025. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6026. * @param startValue defines the start value
  6027. * @param endValue defines the end value
  6028. * @param gradient defines the gradient factor
  6029. * @param result defines the Matrix object where to store data
  6030. */
  6031. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6032. for (var index = 0; index < 16; index++) {
  6033. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6034. }
  6035. result._markAsUpdated();
  6036. };
  6037. /**
  6038. * Builds a new matrix whose values are computed by:
  6039. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6040. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6041. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6042. * @param startValue defines the first matrix
  6043. * @param endValue defines the second matrix
  6044. * @param gradient defines the gradient between the two matrices
  6045. * @returns the new matrix
  6046. */
  6047. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6048. var result = Matrix.Zero();
  6049. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6050. return result;
  6051. };
  6052. /**
  6053. * Update a matrix to values which are computed by:
  6054. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6055. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6056. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6057. * @param startValue defines the first matrix
  6058. * @param endValue defines the second matrix
  6059. * @param gradient defines the gradient between the two matrices
  6060. * @param result defines the target matrix
  6061. */
  6062. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6063. var startScale = MathTmp.Vector3[0];
  6064. var startRotation = MathTmp.Quaternion[0];
  6065. var startTranslation = MathTmp.Vector3[1];
  6066. startValue.decompose(startScale, startRotation, startTranslation);
  6067. var endScale = MathTmp.Vector3[2];
  6068. var endRotation = MathTmp.Quaternion[1];
  6069. var endTranslation = MathTmp.Vector3[3];
  6070. endValue.decompose(endScale, endRotation, endTranslation);
  6071. var resultScale = MathTmp.Vector3[4];
  6072. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6073. var resultRotation = MathTmp.Quaternion[2];
  6074. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6075. var resultTranslation = MathTmp.Vector3[5];
  6076. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6077. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6078. };
  6079. /**
  6080. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6081. * This function works in left handed mode
  6082. * @param eye defines the final position of the entity
  6083. * @param target defines where the entity should look at
  6084. * @param up defines the up vector for the entity
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.LookAtLH = function (eye, target, up) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LookAtLHToRef(eye, target, up, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6094. * This function works in left handed mode
  6095. * @param eye defines the final position of the entity
  6096. * @param target defines where the entity should look at
  6097. * @param up defines the up vector for the entity
  6098. * @param result defines the target matrix
  6099. */
  6100. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6101. // Z axis
  6102. target.subtractToRef(eye, this._zAxis);
  6103. this._zAxis.normalize();
  6104. // X axis
  6105. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6106. if (this._xAxis.lengthSquared() === 0) {
  6107. this._xAxis.x = 1.0;
  6108. }
  6109. else {
  6110. this._xAxis.normalize();
  6111. }
  6112. // Y axis
  6113. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6114. this._yAxis.normalize();
  6115. // Eye angles
  6116. var ex = -Vector3.Dot(this._xAxis, eye);
  6117. var ey = -Vector3.Dot(this._yAxis, eye);
  6118. var ez = -Vector3.Dot(this._zAxis, eye);
  6119. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6120. };
  6121. /**
  6122. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6123. * This function works in right handed mode
  6124. * @param eye defines the final position of the entity
  6125. * @param target defines where the entity should look at
  6126. * @param up defines the up vector for the entity
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.LookAtRH = function (eye, target, up) {
  6130. var result = Matrix.Zero();
  6131. Matrix.LookAtRHToRef(eye, target, up, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6136. * This function works in right handed mode
  6137. * @param eye defines the final position of the entity
  6138. * @param target defines where the entity should look at
  6139. * @param up defines the up vector for the entity
  6140. * @param result defines the target matrix
  6141. */
  6142. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6143. // Z axis
  6144. eye.subtractToRef(target, this._zAxis);
  6145. this._zAxis.normalize();
  6146. // X axis
  6147. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6148. if (this._xAxis.lengthSquared() === 0) {
  6149. this._xAxis.x = 1.0;
  6150. }
  6151. else {
  6152. this._xAxis.normalize();
  6153. }
  6154. // Y axis
  6155. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6156. this._yAxis.normalize();
  6157. // Eye angles
  6158. var ex = -Vector3.Dot(this._xAxis, eye);
  6159. var ey = -Vector3.Dot(this._yAxis, eye);
  6160. var ez = -Vector3.Dot(this._zAxis, eye);
  6161. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6162. };
  6163. /**
  6164. * Create a left-handed orthographic projection matrix
  6165. * @param width defines the viewport width
  6166. * @param height defines the viewport height
  6167. * @param znear defines the near clip plane
  6168. * @param zfar defines the far clip plane
  6169. * @returns a new matrix as a left-handed orthographic projection matrix
  6170. */
  6171. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6172. var matrix = Matrix.Zero();
  6173. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6174. return matrix;
  6175. };
  6176. /**
  6177. * Store a left-handed orthographic projection to a given matrix
  6178. * @param width defines the viewport width
  6179. * @param height defines the viewport height
  6180. * @param znear defines the near clip plane
  6181. * @param zfar defines the far clip plane
  6182. * @param result defines the target matrix
  6183. */
  6184. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6185. var n = znear;
  6186. var f = zfar;
  6187. var a = 2.0 / width;
  6188. var b = 2.0 / height;
  6189. var c = 2.0 / (f - n);
  6190. var d = -(f + n) / (f - n);
  6191. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6192. };
  6193. /**
  6194. * Create a left-handed orthographic projection matrix
  6195. * @param left defines the viewport left coordinate
  6196. * @param right defines the viewport right coordinate
  6197. * @param bottom defines the viewport bottom coordinate
  6198. * @param top defines the viewport top coordinate
  6199. * @param znear defines the near clip plane
  6200. * @param zfar defines the far clip plane
  6201. * @returns a new matrix as a left-handed orthographic projection matrix
  6202. */
  6203. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6204. var matrix = Matrix.Zero();
  6205. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6206. return matrix;
  6207. };
  6208. /**
  6209. * Stores a left-handed orthographic projection into a given matrix
  6210. * @param left defines the viewport left coordinate
  6211. * @param right defines the viewport right coordinate
  6212. * @param bottom defines the viewport bottom coordinate
  6213. * @param top defines the viewport top coordinate
  6214. * @param znear defines the near clip plane
  6215. * @param zfar defines the far clip plane
  6216. * @param result defines the target matrix
  6217. */
  6218. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6219. var n = znear;
  6220. var f = zfar;
  6221. var a = 2.0 / (right - left);
  6222. var b = 2.0 / (top - bottom);
  6223. var c = 2.0 / (f - n);
  6224. var d = -(f + n) / (f - n);
  6225. var i0 = (left + right) / (left - right);
  6226. var i1 = (top + bottom) / (bottom - top);
  6227. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6228. };
  6229. /**
  6230. * Creates a right-handed orthographic projection matrix
  6231. * @param left defines the viewport left coordinate
  6232. * @param right defines the viewport right coordinate
  6233. * @param bottom defines the viewport bottom coordinate
  6234. * @param top defines the viewport top coordinate
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a right-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Stores a right-handed orthographic projection into a given matrix
  6246. * @param left defines the viewport left coordinate
  6247. * @param right defines the viewport right coordinate
  6248. * @param bottom defines the viewport bottom coordinate
  6249. * @param top defines the viewport top coordinate
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6255. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6256. result.m[10] *= -1.0;
  6257. };
  6258. /**
  6259. * Creates a left-handed perspective projection matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @returns a new matrix as a left-handed perspective projection matrix
  6265. */
  6266. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6267. var matrix = Matrix.Zero();
  6268. var n = znear;
  6269. var f = zfar;
  6270. var a = 2.0 * n / width;
  6271. var b = 2.0 * n / height;
  6272. var c = (f + n) / (f - n);
  6273. var d = -2.0 * f * n / (f - n);
  6274. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6275. return matrix;
  6276. };
  6277. /**
  6278. * Creates a left-handed perspective projection matrix
  6279. * @param fov defines the horizontal field of view
  6280. * @param aspect defines the aspect ratio
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed perspective projection matrix
  6284. */
  6285. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed perspective projection into a given matrix
  6292. * @param fov defines the horizontal field of view
  6293. * @param aspect defines the aspect ratio
  6294. * @param znear defines the near clip plane
  6295. * @param zfar defines the far clip plane
  6296. * @param result defines the target matrix
  6297. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6298. */
  6299. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6300. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6301. var n = znear;
  6302. var f = zfar;
  6303. var t = 1.0 / (Math.tan(fov * 0.5));
  6304. var a = isVerticalFovFixed ? (t / aspect) : t;
  6305. var b = isVerticalFovFixed ? t : (t * aspect);
  6306. var c = (f + n) / (f - n);
  6307. var d = -2.0 * f * n / (f - n);
  6308. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6309. };
  6310. /**
  6311. * Creates a right-handed perspective projection matrix
  6312. * @param fov defines the horizontal field of view
  6313. * @param aspect defines the aspect ratio
  6314. * @param znear defines the near clip plane
  6315. * @param zfar defines the far clip plane
  6316. * @returns a new matrix as a right-handed perspective projection matrix
  6317. */
  6318. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6319. var matrix = Matrix.Zero();
  6320. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6321. return matrix;
  6322. };
  6323. /**
  6324. * Stores a right-handed perspective projection into a given matrix
  6325. * @param fov defines the horizontal field of view
  6326. * @param aspect defines the aspect ratio
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @param result defines the target matrix
  6330. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6331. */
  6332. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6333. //alternatively this could be expressed as:
  6334. // m = PerspectiveFovLHToRef
  6335. // m[10] *= -1.0;
  6336. // m[11] *= -1.0;
  6337. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6338. var n = znear;
  6339. var f = zfar;
  6340. var t = 1.0 / (Math.tan(fov * 0.5));
  6341. var a = isVerticalFovFixed ? (t / aspect) : t;
  6342. var b = isVerticalFovFixed ? t : (t * aspect);
  6343. var c = -(f + n) / (f - n);
  6344. var d = -2 * f * n / (f - n);
  6345. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6346. };
  6347. /**
  6348. * Stores a perspective projection for WebVR info a given matrix
  6349. * @param fov defines the field of view
  6350. * @param znear defines the near clip plane
  6351. * @param zfar defines the far clip plane
  6352. * @param result defines the target matrix
  6353. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6354. */
  6355. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6356. if (rightHanded === void 0) { rightHanded = false; }
  6357. var rightHandedFactor = rightHanded ? -1 : 1;
  6358. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6359. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6360. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6361. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6362. var xScale = 2.0 / (leftTan + rightTan);
  6363. var yScale = 2.0 / (upTan + downTan);
  6364. result.m[0] = xScale;
  6365. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6366. result.m[5] = yScale;
  6367. result.m[6] = result.m[7] = 0.0;
  6368. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6369. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6370. result.m[10] = -zfar / (znear - zfar);
  6371. result.m[11] = 1.0 * rightHandedFactor;
  6372. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6373. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6374. result._markAsUpdated();
  6375. };
  6376. /**
  6377. * Computes a complete transformation matrix
  6378. * @param viewport defines the viewport to use
  6379. * @param world defines the world matrix
  6380. * @param view defines the view matrix
  6381. * @param projection defines the projection matrix
  6382. * @param zmin defines the near clip plane
  6383. * @param zmax defines the far clip plane
  6384. * @returns the transformation matrix
  6385. */
  6386. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6387. var cw = viewport.width;
  6388. var ch = viewport.height;
  6389. var cx = viewport.x;
  6390. var cy = viewport.y;
  6391. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6392. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6393. };
  6394. /**
  6395. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6396. * @param matrix defines the matrix to use
  6397. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6398. */
  6399. Matrix.GetAsMatrix2x2 = function (matrix) {
  6400. return new Float32Array([
  6401. matrix.m[0], matrix.m[1],
  6402. matrix.m[4], matrix.m[5]
  6403. ]);
  6404. };
  6405. /**
  6406. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6407. * @param matrix defines the matrix to use
  6408. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6409. */
  6410. Matrix.GetAsMatrix3x3 = function (matrix) {
  6411. return new Float32Array([
  6412. matrix.m[0], matrix.m[1], matrix.m[2],
  6413. matrix.m[4], matrix.m[5], matrix.m[6],
  6414. matrix.m[8], matrix.m[9], matrix.m[10]
  6415. ]);
  6416. };
  6417. /**
  6418. * Compute the transpose of a given matrix
  6419. * @param matrix defines the matrix to transpose
  6420. * @returns the new matrix
  6421. */
  6422. Matrix.Transpose = function (matrix) {
  6423. var result = new Matrix();
  6424. Matrix.TransposeToRef(matrix, result);
  6425. return result;
  6426. };
  6427. /**
  6428. * Compute the transpose of a matrix and store it in a target matrix
  6429. * @param matrix defines the matrix to transpose
  6430. * @param result defines the target matrix
  6431. */
  6432. Matrix.TransposeToRef = function (matrix, result) {
  6433. result.m[0] = matrix.m[0];
  6434. result.m[1] = matrix.m[4];
  6435. result.m[2] = matrix.m[8];
  6436. result.m[3] = matrix.m[12];
  6437. result.m[4] = matrix.m[1];
  6438. result.m[5] = matrix.m[5];
  6439. result.m[6] = matrix.m[9];
  6440. result.m[7] = matrix.m[13];
  6441. result.m[8] = matrix.m[2];
  6442. result.m[9] = matrix.m[6];
  6443. result.m[10] = matrix.m[10];
  6444. result.m[11] = matrix.m[14];
  6445. result.m[12] = matrix.m[3];
  6446. result.m[13] = matrix.m[7];
  6447. result.m[14] = matrix.m[11];
  6448. result.m[15] = matrix.m[15];
  6449. };
  6450. /**
  6451. * Computes a reflection matrix from a plane
  6452. * @param plane defines the reflection plane
  6453. * @returns a new matrix
  6454. */
  6455. Matrix.Reflection = function (plane) {
  6456. var matrix = new Matrix();
  6457. Matrix.ReflectionToRef(plane, matrix);
  6458. return matrix;
  6459. };
  6460. /**
  6461. * Computes a reflection matrix from a plane
  6462. * @param plane defines the reflection plane
  6463. * @param result defines the target matrix
  6464. */
  6465. Matrix.ReflectionToRef = function (plane, result) {
  6466. plane.normalize();
  6467. var x = plane.normal.x;
  6468. var y = plane.normal.y;
  6469. var z = plane.normal.z;
  6470. var temp = -2 * x;
  6471. var temp2 = -2 * y;
  6472. var temp3 = -2 * z;
  6473. result.m[0] = (temp * x) + 1;
  6474. result.m[1] = temp2 * x;
  6475. result.m[2] = temp3 * x;
  6476. result.m[3] = 0.0;
  6477. result.m[4] = temp * y;
  6478. result.m[5] = (temp2 * y) + 1;
  6479. result.m[6] = temp3 * y;
  6480. result.m[7] = 0.0;
  6481. result.m[8] = temp * z;
  6482. result.m[9] = temp2 * z;
  6483. result.m[10] = (temp3 * z) + 1;
  6484. result.m[11] = 0.0;
  6485. result.m[12] = temp * plane.d;
  6486. result.m[13] = temp2 * plane.d;
  6487. result.m[14] = temp3 * plane.d;
  6488. result.m[15] = 1.0;
  6489. result._markAsUpdated();
  6490. };
  6491. /**
  6492. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6493. * @param xaxis defines the value of the 1st axis
  6494. * @param yaxis defines the value of the 2nd axis
  6495. * @param zaxis defines the value of the 3rd axis
  6496. * @param result defines the target matrix
  6497. */
  6498. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6499. result.m[0] = xaxis.x;
  6500. result.m[1] = xaxis.y;
  6501. result.m[2] = xaxis.z;
  6502. result.m[3] = 0.0;
  6503. result.m[4] = yaxis.x;
  6504. result.m[5] = yaxis.y;
  6505. result.m[6] = yaxis.z;
  6506. result.m[7] = 0.0;
  6507. result.m[8] = zaxis.x;
  6508. result.m[9] = zaxis.y;
  6509. result.m[10] = zaxis.z;
  6510. result.m[11] = 0.0;
  6511. result.m[12] = 0.0;
  6512. result.m[13] = 0.0;
  6513. result.m[14] = 0.0;
  6514. result.m[15] = 1.0;
  6515. result._markAsUpdated();
  6516. };
  6517. /**
  6518. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6519. * @param quat defines the quaternion to use
  6520. * @param result defines the target matrix
  6521. */
  6522. Matrix.FromQuaternionToRef = function (quat, result) {
  6523. var xx = quat.x * quat.x;
  6524. var yy = quat.y * quat.y;
  6525. var zz = quat.z * quat.z;
  6526. var xy = quat.x * quat.y;
  6527. var zw = quat.z * quat.w;
  6528. var zx = quat.z * quat.x;
  6529. var yw = quat.y * quat.w;
  6530. var yz = quat.y * quat.z;
  6531. var xw = quat.x * quat.w;
  6532. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6533. result.m[1] = 2.0 * (xy + zw);
  6534. result.m[2] = 2.0 * (zx - yw);
  6535. result.m[3] = 0.0;
  6536. result.m[4] = 2.0 * (xy - zw);
  6537. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6538. result.m[6] = 2.0 * (yz + xw);
  6539. result.m[7] = 0.0;
  6540. result.m[8] = 2.0 * (zx + yw);
  6541. result.m[9] = 2.0 * (yz - xw);
  6542. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6543. result.m[11] = 0.0;
  6544. result.m[12] = 0.0;
  6545. result.m[13] = 0.0;
  6546. result.m[14] = 0.0;
  6547. result.m[15] = 1.0;
  6548. result._markAsUpdated();
  6549. };
  6550. Matrix._tempQuaternion = new Quaternion();
  6551. Matrix._xAxis = Vector3.Zero();
  6552. Matrix._yAxis = Vector3.Zero();
  6553. Matrix._zAxis = Vector3.Zero();
  6554. Matrix._updateFlagSeed = 0;
  6555. Matrix._identityReadOnly = Matrix.Identity();
  6556. return Matrix;
  6557. }());
  6558. BABYLON.Matrix = Matrix;
  6559. var Plane = /** @class */ (function () {
  6560. /**
  6561. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6562. */
  6563. function Plane(a, b, c, d) {
  6564. this.normal = new Vector3(a, b, c);
  6565. this.d = d;
  6566. }
  6567. /**
  6568. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6569. */
  6570. Plane.prototype.asArray = function () {
  6571. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6572. };
  6573. // Methods
  6574. /**
  6575. * Returns a new plane copied from the current Plane.
  6576. */
  6577. Plane.prototype.clone = function () {
  6578. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6579. };
  6580. /**
  6581. * Returns the string "Plane".
  6582. */
  6583. Plane.prototype.getClassName = function () {
  6584. return "Plane";
  6585. };
  6586. /**
  6587. * Returns the Plane hash code.
  6588. */
  6589. Plane.prototype.getHashCode = function () {
  6590. var hash = this.normal.getHashCode();
  6591. hash = (hash * 397) ^ (this.d || 0);
  6592. return hash;
  6593. };
  6594. /**
  6595. * Normalize the current Plane in place.
  6596. * Returns the updated Plane.
  6597. */
  6598. Plane.prototype.normalize = function () {
  6599. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6600. var magnitude = 0.0;
  6601. if (norm !== 0) {
  6602. magnitude = 1.0 / norm;
  6603. }
  6604. this.normal.x *= magnitude;
  6605. this.normal.y *= magnitude;
  6606. this.normal.z *= magnitude;
  6607. this.d *= magnitude;
  6608. return this;
  6609. };
  6610. /**
  6611. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6612. */
  6613. Plane.prototype.transform = function (transformation) {
  6614. var transposedMatrix = Matrix.Transpose(transformation);
  6615. var x = this.normal.x;
  6616. var y = this.normal.y;
  6617. var z = this.normal.z;
  6618. var d = this.d;
  6619. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6620. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6621. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6622. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6623. return new Plane(normalX, normalY, normalZ, finalD);
  6624. };
  6625. /**
  6626. * Returns the dot product (float) of the point coordinates and the plane normal.
  6627. */
  6628. Plane.prototype.dotCoordinate = function (point) {
  6629. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6630. };
  6631. /**
  6632. * Updates the current Plane from the plane defined by the three given points.
  6633. * Returns the updated Plane.
  6634. */
  6635. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6636. var x1 = point2.x - point1.x;
  6637. var y1 = point2.y - point1.y;
  6638. var z1 = point2.z - point1.z;
  6639. var x2 = point3.x - point1.x;
  6640. var y2 = point3.y - point1.y;
  6641. var z2 = point3.z - point1.z;
  6642. var yz = (y1 * z2) - (z1 * y2);
  6643. var xz = (z1 * x2) - (x1 * z2);
  6644. var xy = (x1 * y2) - (y1 * x2);
  6645. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6646. var invPyth;
  6647. if (pyth !== 0) {
  6648. invPyth = 1.0 / pyth;
  6649. }
  6650. else {
  6651. invPyth = 0.0;
  6652. }
  6653. this.normal.x = yz * invPyth;
  6654. this.normal.y = xz * invPyth;
  6655. this.normal.z = xy * invPyth;
  6656. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6657. return this;
  6658. };
  6659. /**
  6660. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6661. */
  6662. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6663. var dot = Vector3.Dot(this.normal, direction);
  6664. return (dot <= epsilon);
  6665. };
  6666. /**
  6667. * Returns the signed distance (float) from the given point to the Plane.
  6668. */
  6669. Plane.prototype.signedDistanceTo = function (point) {
  6670. return Vector3.Dot(point, this.normal) + this.d;
  6671. };
  6672. // Statics
  6673. /**
  6674. * Returns a new Plane from the given array.
  6675. */
  6676. Plane.FromArray = function (array) {
  6677. return new Plane(array[0], array[1], array[2], array[3]);
  6678. };
  6679. /**
  6680. * Returns a new Plane defined by the three given points.
  6681. */
  6682. Plane.FromPoints = function (point1, point2, point3) {
  6683. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6684. result.copyFromPoints(point1, point2, point3);
  6685. return result;
  6686. };
  6687. /**
  6688. * Returns a new Plane the normal vector to this plane at the given origin point.
  6689. * Note : the vector "normal" is updated because normalized.
  6690. */
  6691. Plane.FromPositionAndNormal = function (origin, normal) {
  6692. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6693. normal.normalize();
  6694. result.normal = normal;
  6695. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6696. return result;
  6697. };
  6698. /**
  6699. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6700. */
  6701. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6702. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6703. return Vector3.Dot(point, normal) + d;
  6704. };
  6705. return Plane;
  6706. }());
  6707. BABYLON.Plane = Plane;
  6708. var Viewport = /** @class */ (function () {
  6709. /**
  6710. * Creates a Viewport object located at (x, y) and sized (width, height).
  6711. */
  6712. function Viewport(x, y, width, height) {
  6713. this.x = x;
  6714. this.y = y;
  6715. this.width = width;
  6716. this.height = height;
  6717. }
  6718. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6719. if (renderWidthOrEngine.getRenderWidth) {
  6720. var engine = renderWidthOrEngine;
  6721. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6722. }
  6723. var renderWidth = renderWidthOrEngine;
  6724. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6725. };
  6726. /**
  6727. * Returns a new Viewport copied from the current one.
  6728. */
  6729. Viewport.prototype.clone = function () {
  6730. return new Viewport(this.x, this.y, this.width, this.height);
  6731. };
  6732. return Viewport;
  6733. }());
  6734. BABYLON.Viewport = Viewport;
  6735. var Frustum = /** @class */ (function () {
  6736. function Frustum() {
  6737. }
  6738. /**
  6739. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6740. */
  6741. Frustum.GetPlanes = function (transform) {
  6742. var frustumPlanes = [];
  6743. for (var index = 0; index < 6; index++) {
  6744. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6745. }
  6746. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6747. return frustumPlanes;
  6748. };
  6749. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6750. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6751. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6752. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6753. frustumPlane.d = transform.m[15] + transform.m[14];
  6754. frustumPlane.normalize();
  6755. };
  6756. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6757. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6758. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6759. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6760. frustumPlane.d = transform.m[15] - transform.m[14];
  6761. frustumPlane.normalize();
  6762. };
  6763. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6764. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6765. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6766. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6767. frustumPlane.d = transform.m[15] + transform.m[12];
  6768. frustumPlane.normalize();
  6769. };
  6770. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6771. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6772. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6773. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6774. frustumPlane.d = transform.m[15] - transform.m[12];
  6775. frustumPlane.normalize();
  6776. };
  6777. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6778. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6779. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6780. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6781. frustumPlane.d = transform.m[15] - transform.m[13];
  6782. frustumPlane.normalize();
  6783. };
  6784. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6785. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6786. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6787. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6788. frustumPlane.d = transform.m[15] + transform.m[13];
  6789. frustumPlane.normalize();
  6790. };
  6791. /**
  6792. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6793. */
  6794. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6795. // Near
  6796. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6797. // Far
  6798. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6799. // Left
  6800. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6801. // Right
  6802. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6803. // Top
  6804. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6805. // Bottom
  6806. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6807. };
  6808. return Frustum;
  6809. }());
  6810. BABYLON.Frustum = Frustum;
  6811. /** Defines supported spaces */
  6812. var Space;
  6813. (function (Space) {
  6814. /** Local (object) space */
  6815. Space[Space["LOCAL"] = 0] = "LOCAL";
  6816. /** World space */
  6817. Space[Space["WORLD"] = 1] = "WORLD";
  6818. /** Bone space */
  6819. Space[Space["BONE"] = 2] = "BONE";
  6820. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6821. /** Defines the 3 main axes */
  6822. var Axis = /** @class */ (function () {
  6823. function Axis() {
  6824. }
  6825. /** X axis */
  6826. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6827. /** Y axis */
  6828. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6829. /** Z axis */
  6830. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6831. return Axis;
  6832. }());
  6833. BABYLON.Axis = Axis;
  6834. ;
  6835. var BezierCurve = /** @class */ (function () {
  6836. function BezierCurve() {
  6837. }
  6838. /**
  6839. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6840. */
  6841. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6842. // Extract X (which is equal to time here)
  6843. var f0 = 1 - 3 * x2 + 3 * x1;
  6844. var f1 = 3 * x2 - 6 * x1;
  6845. var f2 = 3 * x1;
  6846. var refinedT = t;
  6847. for (var i = 0; i < 5; i++) {
  6848. var refinedT2 = refinedT * refinedT;
  6849. var refinedT3 = refinedT2 * refinedT;
  6850. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6851. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6852. refinedT -= (x - t) * slope;
  6853. refinedT = Math.min(1, Math.max(0, refinedT));
  6854. }
  6855. // Resolve cubic bezier for the given x
  6856. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6857. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6858. Math.pow(refinedT, 3);
  6859. };
  6860. return BezierCurve;
  6861. }());
  6862. BABYLON.BezierCurve = BezierCurve;
  6863. /**
  6864. * Defines potential orientation for back face culling
  6865. */
  6866. var Orientation;
  6867. (function (Orientation) {
  6868. /**
  6869. * Clockwise
  6870. */
  6871. Orientation[Orientation["CW"] = 0] = "CW";
  6872. /** Counter clockwise */
  6873. Orientation[Orientation["CCW"] = 1] = "CCW";
  6874. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6875. /**
  6876. * Defines angle representation
  6877. */
  6878. var Angle = /** @class */ (function () {
  6879. /**
  6880. * Creates an Angle object of "radians" radians (float).
  6881. */
  6882. function Angle(radians) {
  6883. this._radians = radians;
  6884. if (this._radians < 0.0)
  6885. this._radians += (2.0 * Math.PI);
  6886. }
  6887. /**
  6888. * Get value in degrees
  6889. * @returns the Angle value in degrees (float)
  6890. */
  6891. Angle.prototype.degrees = function () {
  6892. return this._radians * 180.0 / Math.PI;
  6893. };
  6894. /**
  6895. * Get value in radians
  6896. * @returns the Angle value in radians (float)
  6897. */
  6898. Angle.prototype.radians = function () {
  6899. return this._radians;
  6900. };
  6901. /**
  6902. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6903. * @param a defines first vector
  6904. * @param b defines second vector
  6905. * @returns a new Angle
  6906. */
  6907. Angle.BetweenTwoPoints = function (a, b) {
  6908. var delta = b.subtract(a);
  6909. var theta = Math.atan2(delta.y, delta.x);
  6910. return new Angle(theta);
  6911. };
  6912. /**
  6913. * Gets a new Angle object from the given float in radians
  6914. * @param radians defines the angle value in radians
  6915. * @returns a new Angle
  6916. */
  6917. Angle.FromRadians = function (radians) {
  6918. return new Angle(radians);
  6919. };
  6920. /**
  6921. * Gets a new Angle object from the given float in degrees
  6922. * @param degrees defines the angle value in degrees
  6923. * @returns a new Angle
  6924. */
  6925. Angle.FromDegrees = function (degrees) {
  6926. return new Angle(degrees * Math.PI / 180.0);
  6927. };
  6928. return Angle;
  6929. }());
  6930. BABYLON.Angle = Angle;
  6931. var Arc2 = /** @class */ (function () {
  6932. /**
  6933. * Creates an Arc object from the three given points : start, middle and end.
  6934. */
  6935. function Arc2(startPoint, midPoint, endPoint) {
  6936. this.startPoint = startPoint;
  6937. this.midPoint = midPoint;
  6938. this.endPoint = endPoint;
  6939. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6940. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6941. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6942. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6943. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6944. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6945. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6946. var a1 = this.startAngle.degrees();
  6947. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6948. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6949. // angles correction
  6950. if (a2 - a1 > +180.0)
  6951. a2 -= 360.0;
  6952. if (a2 - a1 < -180.0)
  6953. a2 += 360.0;
  6954. if (a3 - a2 > +180.0)
  6955. a3 -= 360.0;
  6956. if (a3 - a2 < -180.0)
  6957. a3 += 360.0;
  6958. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6959. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6960. }
  6961. return Arc2;
  6962. }());
  6963. BABYLON.Arc2 = Arc2;
  6964. var Path2 = /** @class */ (function () {
  6965. /**
  6966. * Creates a Path2 object from the starting 2D coordinates x and y.
  6967. */
  6968. function Path2(x, y) {
  6969. this._points = new Array();
  6970. this._length = 0.0;
  6971. this.closed = false;
  6972. this._points.push(new Vector2(x, y));
  6973. }
  6974. /**
  6975. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6976. * Returns the updated Path2.
  6977. */
  6978. Path2.prototype.addLineTo = function (x, y) {
  6979. if (this.closed) {
  6980. return this;
  6981. }
  6982. var newPoint = new Vector2(x, y);
  6983. var previousPoint = this._points[this._points.length - 1];
  6984. this._points.push(newPoint);
  6985. this._length += newPoint.subtract(previousPoint).length();
  6986. return this;
  6987. };
  6988. /**
  6989. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6990. * Returns the updated Path2.
  6991. */
  6992. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6993. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6994. if (this.closed) {
  6995. return this;
  6996. }
  6997. var startPoint = this._points[this._points.length - 1];
  6998. var midPoint = new Vector2(midX, midY);
  6999. var endPoint = new Vector2(endX, endY);
  7000. var arc = new Arc2(startPoint, midPoint, endPoint);
  7001. var increment = arc.angle.radians() / numberOfSegments;
  7002. if (arc.orientation === Orientation.CW)
  7003. increment *= -1;
  7004. var currentAngle = arc.startAngle.radians() + increment;
  7005. for (var i = 0; i < numberOfSegments; i++) {
  7006. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7007. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7008. this.addLineTo(x, y);
  7009. currentAngle += increment;
  7010. }
  7011. return this;
  7012. };
  7013. /**
  7014. * Closes the Path2.
  7015. * Returns the Path2.
  7016. */
  7017. Path2.prototype.close = function () {
  7018. this.closed = true;
  7019. return this;
  7020. };
  7021. /**
  7022. * Returns the Path2 total length (float).
  7023. */
  7024. Path2.prototype.length = function () {
  7025. var result = this._length;
  7026. if (!this.closed) {
  7027. var lastPoint = this._points[this._points.length - 1];
  7028. var firstPoint = this._points[0];
  7029. result += (firstPoint.subtract(lastPoint).length());
  7030. }
  7031. return result;
  7032. };
  7033. /**
  7034. * Returns the Path2 internal array of points.
  7035. */
  7036. Path2.prototype.getPoints = function () {
  7037. return this._points;
  7038. };
  7039. /**
  7040. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7041. */
  7042. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7043. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7044. return Vector2.Zero();
  7045. }
  7046. var lengthPosition = normalizedLengthPosition * this.length();
  7047. var previousOffset = 0;
  7048. for (var i = 0; i < this._points.length; i++) {
  7049. var j = (i + 1) % this._points.length;
  7050. var a = this._points[i];
  7051. var b = this._points[j];
  7052. var bToA = b.subtract(a);
  7053. var nextOffset = (bToA.length() + previousOffset);
  7054. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7055. var dir = bToA.normalize();
  7056. var localOffset = lengthPosition - previousOffset;
  7057. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7058. }
  7059. previousOffset = nextOffset;
  7060. }
  7061. return Vector2.Zero();
  7062. };
  7063. /**
  7064. * Returns a new Path2 starting at the coordinates (x, y).
  7065. */
  7066. Path2.StartingAt = function (x, y) {
  7067. return new Path2(x, y);
  7068. };
  7069. return Path2;
  7070. }());
  7071. BABYLON.Path2 = Path2;
  7072. var Path3D = /** @class */ (function () {
  7073. /**
  7074. * new Path3D(path, normal, raw)
  7075. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7076. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7077. * path : an array of Vector3, the curve axis of the Path3D
  7078. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7079. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7080. */
  7081. function Path3D(path, firstNormal, raw) {
  7082. if (firstNormal === void 0) { firstNormal = null; }
  7083. this.path = path;
  7084. this._curve = new Array();
  7085. this._distances = new Array();
  7086. this._tangents = new Array();
  7087. this._normals = new Array();
  7088. this._binormals = new Array();
  7089. for (var p = 0; p < path.length; p++) {
  7090. this._curve[p] = path[p].clone(); // hard copy
  7091. }
  7092. this._raw = raw || false;
  7093. this._compute(firstNormal);
  7094. }
  7095. /**
  7096. * Returns the Path3D array of successive Vector3 designing its curve.
  7097. */
  7098. Path3D.prototype.getCurve = function () {
  7099. return this._curve;
  7100. };
  7101. /**
  7102. * Returns an array populated with tangent vectors on each Path3D curve point.
  7103. */
  7104. Path3D.prototype.getTangents = function () {
  7105. return this._tangents;
  7106. };
  7107. /**
  7108. * Returns an array populated with normal vectors on each Path3D curve point.
  7109. */
  7110. Path3D.prototype.getNormals = function () {
  7111. return this._normals;
  7112. };
  7113. /**
  7114. * Returns an array populated with binormal vectors on each Path3D curve point.
  7115. */
  7116. Path3D.prototype.getBinormals = function () {
  7117. return this._binormals;
  7118. };
  7119. /**
  7120. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7121. */
  7122. Path3D.prototype.getDistances = function () {
  7123. return this._distances;
  7124. };
  7125. /**
  7126. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7127. * Returns the same object updated.
  7128. */
  7129. Path3D.prototype.update = function (path, firstNormal) {
  7130. if (firstNormal === void 0) { firstNormal = null; }
  7131. for (var p = 0; p < path.length; p++) {
  7132. this._curve[p].x = path[p].x;
  7133. this._curve[p].y = path[p].y;
  7134. this._curve[p].z = path[p].z;
  7135. }
  7136. this._compute(firstNormal);
  7137. return this;
  7138. };
  7139. // private function compute() : computes tangents, normals and binormals
  7140. Path3D.prototype._compute = function (firstNormal) {
  7141. var l = this._curve.length;
  7142. // first and last tangents
  7143. this._tangents[0] = this._getFirstNonNullVector(0);
  7144. if (!this._raw) {
  7145. this._tangents[0].normalize();
  7146. }
  7147. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7148. if (!this._raw) {
  7149. this._tangents[l - 1].normalize();
  7150. }
  7151. // normals and binormals at first point : arbitrary vector with _normalVector()
  7152. var tg0 = this._tangents[0];
  7153. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7154. this._normals[0] = pp0;
  7155. if (!this._raw) {
  7156. this._normals[0].normalize();
  7157. }
  7158. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7159. if (!this._raw) {
  7160. this._binormals[0].normalize();
  7161. }
  7162. this._distances[0] = 0.0;
  7163. // normals and binormals : next points
  7164. var prev; // previous vector (segment)
  7165. var cur; // current vector (segment)
  7166. var curTang; // current tangent
  7167. // previous normal
  7168. var prevBinor; // previous binormal
  7169. for (var i = 1; i < l; i++) {
  7170. // tangents
  7171. prev = this._getLastNonNullVector(i);
  7172. if (i < l - 1) {
  7173. cur = this._getFirstNonNullVector(i);
  7174. this._tangents[i] = prev.add(cur);
  7175. this._tangents[i].normalize();
  7176. }
  7177. this._distances[i] = this._distances[i - 1] + prev.length();
  7178. // normals and binormals
  7179. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7180. curTang = this._tangents[i];
  7181. prevBinor = this._binormals[i - 1];
  7182. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7183. if (!this._raw) {
  7184. this._normals[i].normalize();
  7185. }
  7186. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7187. if (!this._raw) {
  7188. this._binormals[i].normalize();
  7189. }
  7190. }
  7191. };
  7192. // private function getFirstNonNullVector(index)
  7193. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7194. Path3D.prototype._getFirstNonNullVector = function (index) {
  7195. var i = 1;
  7196. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7197. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7198. i++;
  7199. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7200. }
  7201. return nNVector;
  7202. };
  7203. // private function getLastNonNullVector(index)
  7204. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7205. Path3D.prototype._getLastNonNullVector = function (index) {
  7206. var i = 1;
  7207. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7208. while (nLVector.length() === 0 && index > i + 1) {
  7209. i++;
  7210. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7211. }
  7212. return nLVector;
  7213. };
  7214. // private function normalVector(v0, vt, va) :
  7215. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7216. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7217. Path3D.prototype._normalVector = function (v0, vt, va) {
  7218. var normal0;
  7219. var tgl = vt.length();
  7220. if (tgl === 0.0) {
  7221. tgl = 1.0;
  7222. }
  7223. if (va === undefined || va === null) {
  7224. var point;
  7225. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7226. point = new Vector3(0.0, -1.0, 0.0);
  7227. }
  7228. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7229. point = new Vector3(1.0, 0.0, 0.0);
  7230. }
  7231. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7232. point = new Vector3(0.0, 0.0, 1.0);
  7233. }
  7234. else {
  7235. point = Vector3.Zero();
  7236. }
  7237. normal0 = Vector3.Cross(vt, point);
  7238. }
  7239. else {
  7240. normal0 = Vector3.Cross(vt, va);
  7241. Vector3.CrossToRef(normal0, vt, normal0);
  7242. }
  7243. normal0.normalize();
  7244. return normal0;
  7245. };
  7246. return Path3D;
  7247. }());
  7248. BABYLON.Path3D = Path3D;
  7249. var Curve3 = /** @class */ (function () {
  7250. /**
  7251. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7252. * A Curve3 is designed from a series of successive Vector3.
  7253. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7254. */
  7255. function Curve3(points) {
  7256. this._length = 0.0;
  7257. this._points = points;
  7258. this._length = this._computeLength(points);
  7259. }
  7260. /**
  7261. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7262. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7263. * @param v1 (Vector3) the control point
  7264. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7265. * @param nbPoints (integer) the wanted number of points in the curve
  7266. */
  7267. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7268. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7269. var bez = new Array();
  7270. var equation = function (t, val0, val1, val2) {
  7271. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7272. return res;
  7273. };
  7274. for (var i = 0; i <= nbPoints; i++) {
  7275. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7276. }
  7277. return new Curve3(bez);
  7278. };
  7279. /**
  7280. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7281. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7282. * @param v1 (Vector3) the first control point
  7283. * @param v2 (Vector3) the second control point
  7284. * @param v3 (Vector3) the end point of the Cubic Bezier
  7285. * @param nbPoints (integer) the wanted number of points in the curve
  7286. */
  7287. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7288. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7289. var bez = new Array();
  7290. var equation = function (t, val0, val1, val2, val3) {
  7291. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7292. return res;
  7293. };
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7296. }
  7297. return new Curve3(bez);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7301. * @param p1 (Vector3) the origin point of the Hermite Spline
  7302. * @param t1 (Vector3) the tangent vector at the origin point
  7303. * @param p2 (Vector3) the end point of the Hermite Spline
  7304. * @param t2 (Vector3) the tangent vector at the end point
  7305. * @param nbPoints (integer) the wanted number of points in the curve
  7306. */
  7307. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7308. var hermite = new Array();
  7309. var step = 1.0 / nbPoints;
  7310. for (var i = 0; i <= nbPoints; i++) {
  7311. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7312. }
  7313. return new Curve3(hermite);
  7314. };
  7315. /**
  7316. * Returns a Curve3 object along a CatmullRom Spline curve :
  7317. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7318. * @param nbPoints (integer) the wanted number of points between each curve control points
  7319. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7320. */
  7321. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7322. var catmullRom = new Array();
  7323. var step = 1.0 / nbPoints;
  7324. var amount = 0.0;
  7325. if (closed) {
  7326. var pointsCount = points.length;
  7327. for (var i = 0; i < pointsCount; i++) {
  7328. amount = 0;
  7329. for (var c = 0; c < nbPoints; c++) {
  7330. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7331. amount += step;
  7332. }
  7333. }
  7334. catmullRom.push(catmullRom[0]);
  7335. }
  7336. else {
  7337. var totalPoints = new Array();
  7338. totalPoints.push(points[0].clone());
  7339. Array.prototype.push.apply(totalPoints, points);
  7340. totalPoints.push(points[points.length - 1].clone());
  7341. for (var i = 0; i < totalPoints.length - 3; i++) {
  7342. amount = 0;
  7343. for (var c = 0; c < nbPoints; c++) {
  7344. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7345. amount += step;
  7346. }
  7347. }
  7348. i--;
  7349. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7350. }
  7351. return new Curve3(catmullRom);
  7352. };
  7353. /**
  7354. * Returns the Curve3 stored array of successive Vector3
  7355. */
  7356. Curve3.prototype.getPoints = function () {
  7357. return this._points;
  7358. };
  7359. /**
  7360. * Returns the computed length (float) of the curve.
  7361. */
  7362. Curve3.prototype.length = function () {
  7363. return this._length;
  7364. };
  7365. /**
  7366. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7367. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7368. * curveA and curveB keep unchanged.
  7369. */
  7370. Curve3.prototype.continue = function (curve) {
  7371. var lastPoint = this._points[this._points.length - 1];
  7372. var continuedPoints = this._points.slice();
  7373. var curvePoints = curve.getPoints();
  7374. for (var i = 1; i < curvePoints.length; i++) {
  7375. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7376. }
  7377. var continuedCurve = new Curve3(continuedPoints);
  7378. return continuedCurve;
  7379. };
  7380. Curve3.prototype._computeLength = function (path) {
  7381. var l = 0;
  7382. for (var i = 1; i < path.length; i++) {
  7383. l += (path[i].subtract(path[i - 1])).length();
  7384. }
  7385. return l;
  7386. };
  7387. return Curve3;
  7388. }());
  7389. BABYLON.Curve3 = Curve3;
  7390. // Vertex formats
  7391. var PositionNormalVertex = /** @class */ (function () {
  7392. function PositionNormalVertex(position, normal) {
  7393. if (position === void 0) { position = Vector3.Zero(); }
  7394. if (normal === void 0) { normal = Vector3.Up(); }
  7395. this.position = position;
  7396. this.normal = normal;
  7397. }
  7398. PositionNormalVertex.prototype.clone = function () {
  7399. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7400. };
  7401. return PositionNormalVertex;
  7402. }());
  7403. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7404. var PositionNormalTextureVertex = /** @class */ (function () {
  7405. function PositionNormalTextureVertex(position, normal, uv) {
  7406. if (position === void 0) { position = Vector3.Zero(); }
  7407. if (normal === void 0) { normal = Vector3.Up(); }
  7408. if (uv === void 0) { uv = Vector2.Zero(); }
  7409. this.position = position;
  7410. this.normal = normal;
  7411. this.uv = uv;
  7412. }
  7413. PositionNormalTextureVertex.prototype.clone = function () {
  7414. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7415. };
  7416. return PositionNormalTextureVertex;
  7417. }());
  7418. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7419. // Temporary pre-allocated objects for engine internal use
  7420. // usage in any internal function :
  7421. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7422. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7423. var Tmp = /** @class */ (function () {
  7424. function Tmp() {
  7425. }
  7426. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7427. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7428. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7429. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7430. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7431. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7432. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7433. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7434. Matrix.Zero(), Matrix.Zero(),
  7435. Matrix.Zero(), Matrix.Zero(),
  7436. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7437. return Tmp;
  7438. }());
  7439. BABYLON.Tmp = Tmp;
  7440. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7441. var MathTmp = /** @class */ (function () {
  7442. function MathTmp() {
  7443. }
  7444. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7445. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7446. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7447. return MathTmp;
  7448. }());
  7449. })(BABYLON || (BABYLON = {}));
  7450. //# sourceMappingURL=babylon.math.js.map
  7451. var BABYLON;
  7452. (function (BABYLON) {
  7453. var Scalar = /** @class */ (function () {
  7454. function Scalar() {
  7455. }
  7456. /**
  7457. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7458. */
  7459. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7460. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7461. var num = a - b;
  7462. return -epsilon <= num && num <= epsilon;
  7463. };
  7464. /**
  7465. * Returns a string : the upper case translation of the number i to hexadecimal.
  7466. */
  7467. Scalar.ToHex = function (i) {
  7468. var str = i.toString(16);
  7469. if (i <= 15) {
  7470. return ("0" + str).toUpperCase();
  7471. }
  7472. return str.toUpperCase();
  7473. };
  7474. /**
  7475. * Returns -1 if value is negative and +1 is value is positive.
  7476. * Returns the value itself if it's equal to zero.
  7477. */
  7478. Scalar.Sign = function (value) {
  7479. value = +value; // convert to a number
  7480. if (value === 0 || isNaN(value))
  7481. return value;
  7482. return value > 0 ? 1 : -1;
  7483. };
  7484. /**
  7485. * Returns the value itself if it's between min and max.
  7486. * Returns min if the value is lower than min.
  7487. * Returns max if the value is greater than max.
  7488. */
  7489. Scalar.Clamp = function (value, min, max) {
  7490. if (min === void 0) { min = 0; }
  7491. if (max === void 0) { max = 1; }
  7492. return Math.min(max, Math.max(min, value));
  7493. };
  7494. /**
  7495. * Returns the log2 of value.
  7496. */
  7497. Scalar.Log2 = function (value) {
  7498. return Math.log(value) * Math.LOG2E;
  7499. };
  7500. /**
  7501. * Loops the value, so that it is never larger than length and never smaller than 0.
  7502. *
  7503. * This is similar to the modulo operator but it works with floating point numbers.
  7504. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7505. * With t = 5 and length = 2.5, the result would be 0.0.
  7506. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7507. */
  7508. Scalar.Repeat = function (value, length) {
  7509. return value - Math.floor(value / length) * length;
  7510. };
  7511. /**
  7512. * Normalize the value between 0.0 and 1.0 using min and max values
  7513. */
  7514. Scalar.Normalize = function (value, min, max) {
  7515. return (value - min) / (max - min);
  7516. };
  7517. /**
  7518. * Denormalize the value from 0.0 and 1.0 using min and max values
  7519. */
  7520. Scalar.Denormalize = function (normalized, min, max) {
  7521. return (normalized * (max - min) + min);
  7522. };
  7523. /**
  7524. * Calculates the shortest difference between two given angles given in degrees.
  7525. */
  7526. Scalar.DeltaAngle = function (current, target) {
  7527. var num = Scalar.Repeat(target - current, 360.0);
  7528. if (num > 180.0) {
  7529. num -= 360.0;
  7530. }
  7531. return num;
  7532. };
  7533. /**
  7534. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7535. *
  7536. * The returned value will move back and forth between 0 and length
  7537. */
  7538. Scalar.PingPong = function (tx, length) {
  7539. var t = Scalar.Repeat(tx, length * 2.0);
  7540. return length - Math.abs(t - length);
  7541. };
  7542. /**
  7543. * Interpolates between min and max with smoothing at the limits.
  7544. *
  7545. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7546. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7547. */
  7548. Scalar.SmoothStep = function (from, to, tx) {
  7549. var t = Scalar.Clamp(tx);
  7550. t = -2.0 * t * t * t + 3.0 * t * t;
  7551. return to * t + from * (1.0 - t);
  7552. };
  7553. /**
  7554. * Moves a value current towards target.
  7555. *
  7556. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7557. * Negative values of maxDelta pushes the value away from target.
  7558. */
  7559. Scalar.MoveTowards = function (current, target, maxDelta) {
  7560. var result = 0;
  7561. if (Math.abs(target - current) <= maxDelta) {
  7562. result = target;
  7563. }
  7564. else {
  7565. result = current + Scalar.Sign(target - current) * maxDelta;
  7566. }
  7567. return result;
  7568. };
  7569. /**
  7570. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7571. *
  7572. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7573. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7574. */
  7575. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7576. var num = Scalar.DeltaAngle(current, target);
  7577. var result = 0;
  7578. if (-maxDelta < num && num < maxDelta) {
  7579. result = target;
  7580. }
  7581. else {
  7582. target = current + num;
  7583. result = Scalar.MoveTowards(current, target, maxDelta);
  7584. }
  7585. return result;
  7586. };
  7587. /**
  7588. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7589. */
  7590. Scalar.Lerp = function (start, end, amount) {
  7591. return start + ((end - start) * amount);
  7592. };
  7593. /**
  7594. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7595. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7596. */
  7597. Scalar.LerpAngle = function (start, end, amount) {
  7598. var num = Scalar.Repeat(end - start, 360.0);
  7599. if (num > 180.0) {
  7600. num -= 360.0;
  7601. }
  7602. return start + num * Scalar.Clamp(amount);
  7603. };
  7604. /**
  7605. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7606. */
  7607. Scalar.InverseLerp = function (a, b, value) {
  7608. var result = 0;
  7609. if (a != b) {
  7610. result = Scalar.Clamp((value - a) / (b - a));
  7611. }
  7612. else {
  7613. result = 0.0;
  7614. }
  7615. return result;
  7616. };
  7617. /**
  7618. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7619. */
  7620. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7621. var squared = amount * amount;
  7622. var cubed = amount * squared;
  7623. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7624. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7625. var part3 = (cubed - (2.0 * squared)) + amount;
  7626. var part4 = cubed - squared;
  7627. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7628. };
  7629. /**
  7630. * Returns a random float number between and min and max values
  7631. */
  7632. Scalar.RandomRange = function (min, max) {
  7633. if (min === max)
  7634. return min;
  7635. return ((Math.random() * (max - min)) + min);
  7636. };
  7637. /**
  7638. * This function returns percentage of a number in a given range.
  7639. *
  7640. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7641. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7642. */
  7643. Scalar.RangeToPercent = function (number, min, max) {
  7644. return ((number - min) / (max - min));
  7645. };
  7646. /**
  7647. * This function returns number that corresponds to the percentage in a given range.
  7648. *
  7649. * PercentToRange(0.34,0,100) will return 34.
  7650. */
  7651. Scalar.PercentToRange = function (percent, min, max) {
  7652. return ((max - min) * percent + min);
  7653. };
  7654. /**
  7655. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7656. * @param angle The angle to normalize in radian.
  7657. * @return The converted angle.
  7658. */
  7659. Scalar.NormalizeRadians = function (angle) {
  7660. // More precise but slower version kept for reference.
  7661. // angle = angle % Tools.TwoPi;
  7662. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7663. //if (angle > Math.PI) {
  7664. // angle -= Tools.TwoPi;
  7665. //}
  7666. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7667. return angle;
  7668. };
  7669. /**
  7670. * Two pi constants convenient for computation.
  7671. */
  7672. Scalar.TwoPi = Math.PI * 2;
  7673. return Scalar;
  7674. }());
  7675. BABYLON.Scalar = Scalar;
  7676. })(BABYLON || (BABYLON = {}));
  7677. //# sourceMappingURL=babylon.math.scalar.js.map
  7678. //# sourceMappingURL=babylon.mixins.js.map
  7679. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7680. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7681. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7682. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7683. //# sourceMappingURL=babylon.webgl2.js.map
  7684. var BABYLON;
  7685. (function (BABYLON) {
  7686. var __decoratorInitialStore = {};
  7687. var __mergedStore = {};
  7688. var _copySource = function (creationFunction, source, instanciate) {
  7689. var destination = creationFunction();
  7690. // Tags
  7691. if (BABYLON.Tags) {
  7692. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7693. }
  7694. var classStore = getMergedStore(destination);
  7695. // Properties
  7696. for (var property in classStore) {
  7697. var propertyDescriptor = classStore[property];
  7698. var sourceProperty = source[property];
  7699. var propertyType = propertyDescriptor.type;
  7700. if (sourceProperty !== undefined && sourceProperty !== null) {
  7701. switch (propertyType) {
  7702. case 0: // Value
  7703. case 6: // Mesh reference
  7704. case 11: // Camera reference
  7705. destination[property] = sourceProperty;
  7706. break;
  7707. case 1: // Texture
  7708. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7709. break;
  7710. case 2: // Color3
  7711. case 3: // FresnelParameters
  7712. case 4: // Vector2
  7713. case 5: // Vector3
  7714. case 7: // Color Curves
  7715. case 10: // Quaternion
  7716. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7717. break;
  7718. }
  7719. }
  7720. }
  7721. return destination;
  7722. };
  7723. function getDirectStore(target) {
  7724. var classKey = target.getClassName();
  7725. if (!__decoratorInitialStore[classKey]) {
  7726. __decoratorInitialStore[classKey] = {};
  7727. }
  7728. return __decoratorInitialStore[classKey];
  7729. }
  7730. /**
  7731. * Return the list of properties flagged as serializable
  7732. * @param target: host object
  7733. */
  7734. function getMergedStore(target) {
  7735. var classKey = target.getClassName();
  7736. if (__mergedStore[classKey]) {
  7737. return __mergedStore[classKey];
  7738. }
  7739. __mergedStore[classKey] = {};
  7740. var store = __mergedStore[classKey];
  7741. var currentTarget = target;
  7742. var currentKey = classKey;
  7743. while (currentKey) {
  7744. var initialStore = __decoratorInitialStore[currentKey];
  7745. for (var property in initialStore) {
  7746. store[property] = initialStore[property];
  7747. }
  7748. var parent_1 = void 0;
  7749. var done = false;
  7750. do {
  7751. parent_1 = Object.getPrototypeOf(currentTarget);
  7752. if (!parent_1.getClassName) {
  7753. done = true;
  7754. break;
  7755. }
  7756. if (parent_1.getClassName() !== currentKey) {
  7757. break;
  7758. }
  7759. currentTarget = parent_1;
  7760. } while (parent_1);
  7761. if (done) {
  7762. break;
  7763. }
  7764. currentKey = parent_1.getClassName();
  7765. currentTarget = parent_1;
  7766. }
  7767. return store;
  7768. }
  7769. function generateSerializableMember(type, sourceName) {
  7770. return function (target, propertyKey) {
  7771. var classStore = getDirectStore(target);
  7772. if (!classStore[propertyKey]) {
  7773. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7774. }
  7775. };
  7776. }
  7777. function generateExpandMember(setCallback, targetKey) {
  7778. if (targetKey === void 0) { targetKey = null; }
  7779. return function (target, propertyKey) {
  7780. var key = targetKey || ("_" + propertyKey);
  7781. Object.defineProperty(target, propertyKey, {
  7782. get: function () {
  7783. return this[key];
  7784. },
  7785. set: function (value) {
  7786. if (this[key] === value) {
  7787. return;
  7788. }
  7789. this[key] = value;
  7790. target[setCallback].apply(this);
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. };
  7796. }
  7797. function expandToProperty(callback, targetKey) {
  7798. if (targetKey === void 0) { targetKey = null; }
  7799. return generateExpandMember(callback, targetKey);
  7800. }
  7801. BABYLON.expandToProperty = expandToProperty;
  7802. function serialize(sourceName) {
  7803. return generateSerializableMember(0, sourceName); // value member
  7804. }
  7805. BABYLON.serialize = serialize;
  7806. function serializeAsTexture(sourceName) {
  7807. return generateSerializableMember(1, sourceName); // texture member
  7808. }
  7809. BABYLON.serializeAsTexture = serializeAsTexture;
  7810. function serializeAsColor3(sourceName) {
  7811. return generateSerializableMember(2, sourceName); // color3 member
  7812. }
  7813. BABYLON.serializeAsColor3 = serializeAsColor3;
  7814. function serializeAsFresnelParameters(sourceName) {
  7815. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7816. }
  7817. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7818. function serializeAsVector2(sourceName) {
  7819. return generateSerializableMember(4, sourceName); // vector2 member
  7820. }
  7821. BABYLON.serializeAsVector2 = serializeAsVector2;
  7822. function serializeAsVector3(sourceName) {
  7823. return generateSerializableMember(5, sourceName); // vector3 member
  7824. }
  7825. BABYLON.serializeAsVector3 = serializeAsVector3;
  7826. function serializeAsMeshReference(sourceName) {
  7827. return generateSerializableMember(6, sourceName); // mesh reference member
  7828. }
  7829. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7830. function serializeAsColorCurves(sourceName) {
  7831. return generateSerializableMember(7, sourceName); // color curves
  7832. }
  7833. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7834. function serializeAsColor4(sourceName) {
  7835. return generateSerializableMember(8, sourceName); // color 4
  7836. }
  7837. BABYLON.serializeAsColor4 = serializeAsColor4;
  7838. function serializeAsImageProcessingConfiguration(sourceName) {
  7839. return generateSerializableMember(9, sourceName); // image processing
  7840. }
  7841. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7842. function serializeAsQuaternion(sourceName) {
  7843. return generateSerializableMember(10, sourceName); // quaternion member
  7844. }
  7845. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7846. /**
  7847. * Decorator used to define property that can be serialized as reference to a camera
  7848. * @param sourceName defines the name of the property to decorate
  7849. */
  7850. function serializeAsCameraReference(sourceName) {
  7851. return generateSerializableMember(11, sourceName); // camera reference member
  7852. }
  7853. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7854. var SerializationHelper = /** @class */ (function () {
  7855. function SerializationHelper() {
  7856. }
  7857. SerializationHelper.Serialize = function (entity, serializationObject) {
  7858. if (!serializationObject) {
  7859. serializationObject = {};
  7860. }
  7861. // Tags
  7862. if (BABYLON.Tags) {
  7863. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7864. }
  7865. var serializedProperties = getMergedStore(entity);
  7866. // Properties
  7867. for (var property in serializedProperties) {
  7868. var propertyDescriptor = serializedProperties[property];
  7869. var targetPropertyName = propertyDescriptor.sourceName || property;
  7870. var propertyType = propertyDescriptor.type;
  7871. var sourceProperty = entity[property];
  7872. if (sourceProperty !== undefined && sourceProperty !== null) {
  7873. switch (propertyType) {
  7874. case 0: // Value
  7875. serializationObject[targetPropertyName] = sourceProperty;
  7876. break;
  7877. case 1: // Texture
  7878. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7879. break;
  7880. case 2: // Color3
  7881. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7882. break;
  7883. case 3: // FresnelParameters
  7884. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7885. break;
  7886. case 4: // Vector2
  7887. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7888. break;
  7889. case 5: // Vector3
  7890. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7891. break;
  7892. case 6: // Mesh reference
  7893. serializationObject[targetPropertyName] = sourceProperty.id;
  7894. break;
  7895. case 7: // Color Curves
  7896. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7897. break;
  7898. case 8: // Color 4
  7899. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7900. break;
  7901. case 9: // Image Processing
  7902. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7903. break;
  7904. case 10: // Quaternion
  7905. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7906. break;
  7907. case 11: // Camera reference
  7908. serializationObject[targetPropertyName] = sourceProperty.id;
  7909. break;
  7910. }
  7911. }
  7912. }
  7913. return serializationObject;
  7914. };
  7915. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7916. if (rootUrl === void 0) { rootUrl = null; }
  7917. var destination = creationFunction();
  7918. if (!rootUrl) {
  7919. rootUrl = "";
  7920. }
  7921. // Tags
  7922. if (BABYLON.Tags) {
  7923. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7924. }
  7925. var classStore = getMergedStore(destination);
  7926. // Properties
  7927. for (var property in classStore) {
  7928. var propertyDescriptor = classStore[property];
  7929. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7930. var propertyType = propertyDescriptor.type;
  7931. if (sourceProperty !== undefined && sourceProperty !== null) {
  7932. var dest = destination;
  7933. switch (propertyType) {
  7934. case 0: // Value
  7935. dest[property] = sourceProperty;
  7936. break;
  7937. case 1: // Texture
  7938. if (scene) {
  7939. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7940. }
  7941. break;
  7942. case 2: // Color3
  7943. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7944. break;
  7945. case 3: // FresnelParameters
  7946. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7947. break;
  7948. case 4: // Vector2
  7949. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7950. break;
  7951. case 5: // Vector3
  7952. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7953. break;
  7954. case 6: // Mesh reference
  7955. if (scene) {
  7956. dest[property] = scene.getLastMeshByID(sourceProperty);
  7957. }
  7958. break;
  7959. case 7: // Color Curves
  7960. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7961. break;
  7962. case 8: // Color 4
  7963. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7964. break;
  7965. case 9: // Image Processing
  7966. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7967. break;
  7968. case 10: // Quaternion
  7969. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7970. break;
  7971. case 11: // Camera reference
  7972. if (scene) {
  7973. dest[property] = scene.getCameraByID(sourceProperty);
  7974. }
  7975. break;
  7976. }
  7977. }
  7978. }
  7979. return destination;
  7980. };
  7981. SerializationHelper.Clone = function (creationFunction, source) {
  7982. return _copySource(creationFunction, source, false);
  7983. };
  7984. SerializationHelper.Instanciate = function (creationFunction, source) {
  7985. return _copySource(creationFunction, source, true);
  7986. };
  7987. return SerializationHelper;
  7988. }());
  7989. BABYLON.SerializationHelper = SerializationHelper;
  7990. })(BABYLON || (BABYLON = {}));
  7991. //# sourceMappingURL=babylon.decorators.js.map
  7992. var BABYLON;
  7993. (function (BABYLON) {
  7994. /**
  7995. * Wrapper class for promise with external resolve and reject.
  7996. */
  7997. var Deferred = /** @class */ (function () {
  7998. /**
  7999. * Constructor for this deferred object.
  8000. */
  8001. function Deferred() {
  8002. var _this = this;
  8003. this.promise = new Promise(function (resolve, reject) {
  8004. _this._resolve = resolve;
  8005. _this._reject = reject;
  8006. });
  8007. }
  8008. Object.defineProperty(Deferred.prototype, "resolve", {
  8009. /**
  8010. * The resolve method of the promise associated with this deferred object.
  8011. */
  8012. get: function () {
  8013. return this._resolve;
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Deferred.prototype, "reject", {
  8019. /**
  8020. * The reject method of the promise associated with this deferred object.
  8021. */
  8022. get: function () {
  8023. return this._reject;
  8024. },
  8025. enumerable: true,
  8026. configurable: true
  8027. });
  8028. return Deferred;
  8029. }());
  8030. BABYLON.Deferred = Deferred;
  8031. })(BABYLON || (BABYLON = {}));
  8032. //# sourceMappingURL=babylon.deferred.js.map
  8033. var BABYLON;
  8034. (function (BABYLON) {
  8035. /**
  8036. * A class serves as a medium between the observable and its observers
  8037. */
  8038. var EventState = /** @class */ (function () {
  8039. /**
  8040. * Create a new EventState
  8041. * @param mask defines the mask associated with this state
  8042. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8043. * @param target defines the original target of the state
  8044. * @param currentTarget defines the current target of the state
  8045. */
  8046. function EventState(mask, skipNextObservers, target, currentTarget) {
  8047. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8048. this.initalize(mask, skipNextObservers, target, currentTarget);
  8049. }
  8050. /**
  8051. * Initialize the current event state
  8052. * @param mask defines the mask associated with this state
  8053. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8054. * @param target defines the original target of the state
  8055. * @param currentTarget defines the current target of the state
  8056. * @returns the current event state
  8057. */
  8058. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8059. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8060. this.mask = mask;
  8061. this.skipNextObservers = skipNextObservers;
  8062. this.target = target;
  8063. this.currentTarget = currentTarget;
  8064. return this;
  8065. };
  8066. return EventState;
  8067. }());
  8068. BABYLON.EventState = EventState;
  8069. /**
  8070. * Represent an Observer registered to a given Observable object.
  8071. */
  8072. var Observer = /** @class */ (function () {
  8073. /**
  8074. * Creates a new observer
  8075. * @param callback defines the callback to call when the observer is notified
  8076. * @param mask defines the mask of the observer (used to filter notifications)
  8077. * @param scope defines the current scope used to restore the JS context
  8078. */
  8079. function Observer(
  8080. /**
  8081. * Defines the callback to call when the observer is notified
  8082. */
  8083. callback,
  8084. /**
  8085. * Defines the mask of the observer (used to filter notifications)
  8086. */
  8087. mask,
  8088. /**
  8089. * Defines the current scope used to restore the JS context
  8090. */
  8091. scope) {
  8092. if (scope === void 0) { scope = null; }
  8093. this.callback = callback;
  8094. this.mask = mask;
  8095. this.scope = scope;
  8096. /** @hidden */
  8097. this._willBeUnregistered = false;
  8098. /**
  8099. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8100. */
  8101. this.unregisterOnNextCall = false;
  8102. }
  8103. return Observer;
  8104. }());
  8105. BABYLON.Observer = Observer;
  8106. /**
  8107. * Represent a list of observers registered to multiple Observables object.
  8108. */
  8109. var MultiObserver = /** @class */ (function () {
  8110. function MultiObserver() {
  8111. }
  8112. /**
  8113. * Release associated resources
  8114. */
  8115. MultiObserver.prototype.dispose = function () {
  8116. if (this._observers && this._observables) {
  8117. for (var index = 0; index < this._observers.length; index++) {
  8118. this._observables[index].remove(this._observers[index]);
  8119. }
  8120. }
  8121. this._observers = null;
  8122. this._observables = null;
  8123. };
  8124. /**
  8125. * Raise a callback when one of the observable will notify
  8126. * @param observables defines a list of observables to watch
  8127. * @param callback defines the callback to call on notification
  8128. * @param mask defines the mask used to filter notifications
  8129. * @param scope defines the current scope used to restore the JS context
  8130. * @returns the new MultiObserver
  8131. */
  8132. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8133. if (mask === void 0) { mask = -1; }
  8134. if (scope === void 0) { scope = null; }
  8135. var result = new MultiObserver();
  8136. result._observers = new Array();
  8137. result._observables = observables;
  8138. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8139. var observable = observables_1[_i];
  8140. var observer = observable.add(callback, mask, false, scope);
  8141. if (observer) {
  8142. result._observers.push(observer);
  8143. }
  8144. }
  8145. return result;
  8146. };
  8147. return MultiObserver;
  8148. }());
  8149. BABYLON.MultiObserver = MultiObserver;
  8150. /**
  8151. * The Observable class is a simple implementation of the Observable pattern.
  8152. *
  8153. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8154. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8155. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8156. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8157. */
  8158. var Observable = /** @class */ (function () {
  8159. /**
  8160. * Creates a new observable
  8161. * @param onObserverAdded defines a callback to call when a new observer is added
  8162. */
  8163. function Observable(onObserverAdded) {
  8164. this._observers = new Array();
  8165. this._eventState = new EventState(0);
  8166. if (onObserverAdded) {
  8167. this._onObserverAdded = onObserverAdded;
  8168. }
  8169. }
  8170. /**
  8171. * Create a new Observer with the specified callback
  8172. * @param callback the callback that will be executed for that Observer
  8173. * @param mask the mask used to filter observers
  8174. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8175. * @param scope optional scope for the callback to be called from
  8176. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8177. * @returns the new observer created for the callback
  8178. */
  8179. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8180. if (mask === void 0) { mask = -1; }
  8181. if (insertFirst === void 0) { insertFirst = false; }
  8182. if (scope === void 0) { scope = null; }
  8183. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8184. if (!callback) {
  8185. return null;
  8186. }
  8187. var observer = new Observer(callback, mask, scope);
  8188. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8189. if (insertFirst) {
  8190. this._observers.unshift(observer);
  8191. }
  8192. else {
  8193. this._observers.push(observer);
  8194. }
  8195. if (this._onObserverAdded) {
  8196. this._onObserverAdded(observer);
  8197. }
  8198. return observer;
  8199. };
  8200. /**
  8201. * Create a new Observer with the specified callback and unregisters after the next notification
  8202. * @param callback the callback that will be executed for that Observer
  8203. * @returns the new observer created for the callback
  8204. */
  8205. Observable.prototype.addOnce = function (callback) {
  8206. return this.add(callback, undefined, undefined, undefined, true);
  8207. };
  8208. /**
  8209. * Remove an Observer from the Observable object
  8210. * @param observer the instance of the Observer to remove
  8211. * @returns false if it doesn't belong to this Observable
  8212. */
  8213. Observable.prototype.remove = function (observer) {
  8214. if (!observer) {
  8215. return false;
  8216. }
  8217. var index = this._observers.indexOf(observer);
  8218. if (index !== -1) {
  8219. this._deferUnregister(observer);
  8220. return true;
  8221. }
  8222. return false;
  8223. };
  8224. /**
  8225. * Remove a callback from the Observable object
  8226. * @param callback the callback to remove
  8227. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8228. * @returns false if it doesn't belong to this Observable
  8229. */
  8230. Observable.prototype.removeCallback = function (callback, scope) {
  8231. for (var index = 0; index < this._observers.length; index++) {
  8232. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8233. this._deferUnregister(this._observers[index]);
  8234. return true;
  8235. }
  8236. }
  8237. return false;
  8238. };
  8239. Observable.prototype._deferUnregister = function (observer) {
  8240. var _this = this;
  8241. observer.unregisterOnNextCall = false;
  8242. observer._willBeUnregistered = true;
  8243. BABYLON.Tools.SetImmediate(function () {
  8244. _this._remove(observer);
  8245. });
  8246. };
  8247. // This should only be called when not iterating over _observers to avoid callback skipping.
  8248. // Removes an observer from the _observer Array.
  8249. Observable.prototype._remove = function (observer) {
  8250. if (!observer) {
  8251. return false;
  8252. }
  8253. var index = this._observers.indexOf(observer);
  8254. if (index !== -1) {
  8255. this._observers.splice(index, 1);
  8256. return true;
  8257. }
  8258. return false;
  8259. };
  8260. /**
  8261. * Notify all Observers by calling their respective callback with the given data
  8262. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8263. * @param eventData defines the data to send to all observers
  8264. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8265. * @param target defines the original target of the state
  8266. * @param currentTarget defines the current target of the state
  8267. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8268. */
  8269. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8270. if (mask === void 0) { mask = -1; }
  8271. if (!this._observers.length) {
  8272. return true;
  8273. }
  8274. var state = this._eventState;
  8275. state.mask = mask;
  8276. state.target = target;
  8277. state.currentTarget = currentTarget;
  8278. state.skipNextObservers = false;
  8279. state.lastReturnValue = eventData;
  8280. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8281. var obs = _a[_i];
  8282. if (obs._willBeUnregistered) {
  8283. continue;
  8284. }
  8285. if (obs.mask & mask) {
  8286. if (obs.scope) {
  8287. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8288. }
  8289. else {
  8290. state.lastReturnValue = obs.callback(eventData, state);
  8291. }
  8292. if (obs.unregisterOnNextCall) {
  8293. this._deferUnregister(obs);
  8294. }
  8295. }
  8296. if (state.skipNextObservers) {
  8297. return false;
  8298. }
  8299. }
  8300. return true;
  8301. };
  8302. /**
  8303. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8304. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8305. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8306. * and it is crucial that all callbacks will be executed.
  8307. * The order of the callbacks is kept, callbacks are not executed parallel.
  8308. *
  8309. * @param eventData The data to be sent to each callback
  8310. * @param mask is used to filter observers defaults to -1
  8311. * @param target defines the callback target (see EventState)
  8312. * @param currentTarget defines he current object in the bubbling phase
  8313. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8314. */
  8315. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8316. var _this = this;
  8317. if (mask === void 0) { mask = -1; }
  8318. // create an empty promise
  8319. var p = Promise.resolve(eventData);
  8320. // no observers? return this promise.
  8321. if (!this._observers.length) {
  8322. return p;
  8323. }
  8324. var state = this._eventState;
  8325. state.mask = mask;
  8326. state.target = target;
  8327. state.currentTarget = currentTarget;
  8328. state.skipNextObservers = false;
  8329. // execute one callback after another (not using Promise.all, the order is important)
  8330. this._observers.forEach(function (obs) {
  8331. if (state.skipNextObservers) {
  8332. return;
  8333. }
  8334. if (obs._willBeUnregistered) {
  8335. return;
  8336. }
  8337. if (obs.mask & mask) {
  8338. if (obs.scope) {
  8339. p = p.then(function (lastReturnedValue) {
  8340. state.lastReturnValue = lastReturnedValue;
  8341. return obs.callback.apply(obs.scope, [eventData, state]);
  8342. });
  8343. }
  8344. else {
  8345. p = p.then(function (lastReturnedValue) {
  8346. state.lastReturnValue = lastReturnedValue;
  8347. return obs.callback(eventData, state);
  8348. });
  8349. }
  8350. if (obs.unregisterOnNextCall) {
  8351. _this._deferUnregister(obs);
  8352. }
  8353. }
  8354. });
  8355. // return the eventData
  8356. return p.then(function () { return eventData; });
  8357. };
  8358. /**
  8359. * Notify a specific observer
  8360. * @param observer defines the observer to notify
  8361. * @param eventData defines the data to be sent to each callback
  8362. * @param mask is used to filter observers defaults to -1
  8363. */
  8364. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8365. if (mask === void 0) { mask = -1; }
  8366. var state = this._eventState;
  8367. state.mask = mask;
  8368. state.skipNextObservers = false;
  8369. observer.callback(eventData, state);
  8370. };
  8371. /**
  8372. * Gets a boolean indicating if the observable has at least one observer
  8373. * @returns true is the Observable has at least one Observer registered
  8374. */
  8375. Observable.prototype.hasObservers = function () {
  8376. return this._observers.length > 0;
  8377. };
  8378. /**
  8379. * Clear the list of observers
  8380. */
  8381. Observable.prototype.clear = function () {
  8382. this._observers = new Array();
  8383. this._onObserverAdded = null;
  8384. };
  8385. /**
  8386. * Clone the current observable
  8387. * @returns a new observable
  8388. */
  8389. Observable.prototype.clone = function () {
  8390. var result = new Observable();
  8391. result._observers = this._observers.slice(0);
  8392. return result;
  8393. };
  8394. /**
  8395. * Does this observable handles observer registered with a given mask
  8396. * @param mask defines the mask to be tested
  8397. * @return whether or not one observer registered with the given mask is handeled
  8398. **/
  8399. Observable.prototype.hasSpecificMask = function (mask) {
  8400. if (mask === void 0) { mask = -1; }
  8401. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8402. var obs = _a[_i];
  8403. if (obs.mask & mask || obs.mask === mask) {
  8404. return true;
  8405. }
  8406. }
  8407. return false;
  8408. };
  8409. return Observable;
  8410. }());
  8411. BABYLON.Observable = Observable;
  8412. })(BABYLON || (BABYLON = {}));
  8413. //# sourceMappingURL=babylon.observable.js.map
  8414. var BABYLON;
  8415. (function (BABYLON) {
  8416. var SmartArray = /** @class */ (function () {
  8417. function SmartArray(capacity) {
  8418. this.length = 0;
  8419. this.data = new Array(capacity);
  8420. this._id = SmartArray._GlobalId++;
  8421. }
  8422. SmartArray.prototype.push = function (value) {
  8423. this.data[this.length++] = value;
  8424. if (this.length > this.data.length) {
  8425. this.data.length *= 2;
  8426. }
  8427. };
  8428. SmartArray.prototype.forEach = function (func) {
  8429. for (var index = 0; index < this.length; index++) {
  8430. func(this.data[index]);
  8431. }
  8432. };
  8433. SmartArray.prototype.sort = function (compareFn) {
  8434. this.data.sort(compareFn);
  8435. };
  8436. SmartArray.prototype.reset = function () {
  8437. this.length = 0;
  8438. };
  8439. SmartArray.prototype.dispose = function () {
  8440. this.reset();
  8441. if (this.data) {
  8442. this.data.length = 0;
  8443. this.data = [];
  8444. }
  8445. };
  8446. SmartArray.prototype.concat = function (array) {
  8447. if (array.length === 0) {
  8448. return;
  8449. }
  8450. if (this.length + array.length > this.data.length) {
  8451. this.data.length = (this.length + array.length) * 2;
  8452. }
  8453. for (var index = 0; index < array.length; index++) {
  8454. this.data[this.length++] = (array.data || array)[index];
  8455. }
  8456. };
  8457. SmartArray.prototype.indexOf = function (value) {
  8458. var position = this.data.indexOf(value);
  8459. if (position >= this.length) {
  8460. return -1;
  8461. }
  8462. return position;
  8463. };
  8464. SmartArray.prototype.contains = function (value) {
  8465. return this.data.indexOf(value) !== -1;
  8466. };
  8467. // Statics
  8468. SmartArray._GlobalId = 0;
  8469. return SmartArray;
  8470. }());
  8471. BABYLON.SmartArray = SmartArray;
  8472. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8473. __extends(SmartArrayNoDuplicate, _super);
  8474. function SmartArrayNoDuplicate() {
  8475. var _this = _super !== null && _super.apply(this, arguments) || this;
  8476. _this._duplicateId = 0;
  8477. return _this;
  8478. }
  8479. SmartArrayNoDuplicate.prototype.push = function (value) {
  8480. _super.prototype.push.call(this, value);
  8481. if (!value.__smartArrayFlags) {
  8482. value.__smartArrayFlags = {};
  8483. }
  8484. value.__smartArrayFlags[this._id] = this._duplicateId;
  8485. };
  8486. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8487. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8488. return false;
  8489. }
  8490. this.push(value);
  8491. return true;
  8492. };
  8493. SmartArrayNoDuplicate.prototype.reset = function () {
  8494. _super.prototype.reset.call(this);
  8495. this._duplicateId++;
  8496. };
  8497. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8498. if (array.length === 0) {
  8499. return;
  8500. }
  8501. if (this.length + array.length > this.data.length) {
  8502. this.data.length = (this.length + array.length) * 2;
  8503. }
  8504. for (var index = 0; index < array.length; index++) {
  8505. var item = (array.data || array)[index];
  8506. this.pushNoDuplicate(item);
  8507. }
  8508. };
  8509. return SmartArrayNoDuplicate;
  8510. }(SmartArray));
  8511. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8512. })(BABYLON || (BABYLON = {}));
  8513. //# sourceMappingURL=babylon.smartArray.js.map
  8514. var BABYLON;
  8515. (function (BABYLON) {
  8516. /** Class used to store color gradient */
  8517. var ColorGradient = /** @class */ (function () {
  8518. function ColorGradient() {
  8519. }
  8520. /**
  8521. * Will get a color picked randomly between color1 and color2.
  8522. * If color2 is undefined then color1 will be used
  8523. * @param result defines the target Color4 to store the result in
  8524. */
  8525. ColorGradient.prototype.getColorToRef = function (result) {
  8526. if (!this.color2) {
  8527. result.copyFrom(this.color1);
  8528. return;
  8529. }
  8530. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8531. };
  8532. return ColorGradient;
  8533. }());
  8534. BABYLON.ColorGradient = ColorGradient;
  8535. /** Class used to store factor gradient */
  8536. var FactorGradient = /** @class */ (function () {
  8537. function FactorGradient() {
  8538. }
  8539. /**
  8540. * Will get a number picked randomly between factor1 and factor2.
  8541. * If factor2 is undefined then factor1 will be used
  8542. * @returns the picked number
  8543. */
  8544. FactorGradient.prototype.getFactor = function () {
  8545. if (this.factor2 === undefined) {
  8546. return this.factor1;
  8547. }
  8548. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8549. };
  8550. return FactorGradient;
  8551. }());
  8552. BABYLON.FactorGradient = FactorGradient;
  8553. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8554. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8555. var LoadFileError = /** @class */ (function (_super) {
  8556. __extends(LoadFileError, _super);
  8557. function LoadFileError(message, request) {
  8558. var _this = _super.call(this, message) || this;
  8559. _this.request = request;
  8560. _this.name = "LoadFileError";
  8561. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8562. return _this;
  8563. }
  8564. // Polyfill for Object.setPrototypeOf if necessary.
  8565. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8566. return LoadFileError;
  8567. }(Error));
  8568. BABYLON.LoadFileError = LoadFileError;
  8569. var RetryStrategy = /** @class */ (function () {
  8570. function RetryStrategy() {
  8571. }
  8572. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8573. if (maxRetries === void 0) { maxRetries = 3; }
  8574. if (baseInterval === void 0) { baseInterval = 500; }
  8575. return function (url, request, retryIndex) {
  8576. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8577. return -1;
  8578. }
  8579. return Math.pow(2, retryIndex) * baseInterval;
  8580. };
  8581. };
  8582. return RetryStrategy;
  8583. }());
  8584. BABYLON.RetryStrategy = RetryStrategy;
  8585. // Screenshots
  8586. var screenshotCanvas;
  8587. var cloneValue = function (source, destinationObject) {
  8588. if (!source)
  8589. return null;
  8590. if (source instanceof BABYLON.Mesh) {
  8591. return null;
  8592. }
  8593. if (source instanceof BABYLON.SubMesh) {
  8594. return source.clone(destinationObject);
  8595. }
  8596. else if (source.clone) {
  8597. return source.clone();
  8598. }
  8599. return null;
  8600. };
  8601. var Tools = /** @class */ (function () {
  8602. function Tools() {
  8603. }
  8604. /**
  8605. * Interpolates between a and b via alpha
  8606. * @param a The lower value (returned when alpha = 0)
  8607. * @param b The upper value (returned when alpha = 1)
  8608. * @param alpha The interpolation-factor
  8609. * @return The mixed value
  8610. */
  8611. Tools.Mix = function (a, b, alpha) {
  8612. return a * (1 - alpha) + b * alpha;
  8613. };
  8614. Tools.Instantiate = function (className) {
  8615. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8616. return Tools.RegisteredExternalClasses[className];
  8617. }
  8618. var arr = className.split(".");
  8619. var fn = (window || this);
  8620. for (var i = 0, len = arr.length; i < len; i++) {
  8621. fn = fn[arr[i]];
  8622. }
  8623. if (typeof fn !== "function") {
  8624. return null;
  8625. }
  8626. return fn;
  8627. };
  8628. /**
  8629. * Provides a slice function that will work even on IE
  8630. * @param data defines the array to slice
  8631. * @param start defines the start of the data (optional)
  8632. * @param end defines the end of the data (optional)
  8633. * @returns the new sliced array
  8634. */
  8635. Tools.Slice = function (data, start, end) {
  8636. if (data.slice) {
  8637. return data.slice(start, end);
  8638. }
  8639. return Array.prototype.slice.call(data, start, end);
  8640. };
  8641. Tools.SetImmediate = function (action) {
  8642. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8643. window.setImmediate(action);
  8644. }
  8645. else {
  8646. setTimeout(action, 1);
  8647. }
  8648. };
  8649. Tools.IsExponentOfTwo = function (value) {
  8650. var count = 1;
  8651. do {
  8652. count *= 2;
  8653. } while (count < value);
  8654. return count === value;
  8655. };
  8656. /**
  8657. * Returns the nearest 32-bit single precision float representation of a Number
  8658. * @param value A Number. If the parameter is of a different type, it will get converted
  8659. * to a number or to NaN if it cannot be converted
  8660. * @returns number
  8661. */
  8662. Tools.FloatRound = function (value) {
  8663. if (Math.fround) {
  8664. return Math.fround(value);
  8665. }
  8666. return (Tools._tmpFloatArray[0] = value);
  8667. };
  8668. /**
  8669. * Find the next highest power of two.
  8670. * @param x Number to start search from.
  8671. * @return Next highest power of two.
  8672. */
  8673. Tools.CeilingPOT = function (x) {
  8674. x--;
  8675. x |= x >> 1;
  8676. x |= x >> 2;
  8677. x |= x >> 4;
  8678. x |= x >> 8;
  8679. x |= x >> 16;
  8680. x++;
  8681. return x;
  8682. };
  8683. /**
  8684. * Find the next lowest power of two.
  8685. * @param x Number to start search from.
  8686. * @return Next lowest power of two.
  8687. */
  8688. Tools.FloorPOT = function (x) {
  8689. x = x | (x >> 1);
  8690. x = x | (x >> 2);
  8691. x = x | (x >> 4);
  8692. x = x | (x >> 8);
  8693. x = x | (x >> 16);
  8694. return x - (x >> 1);
  8695. };
  8696. /**
  8697. * Find the nearest power of two.
  8698. * @param x Number to start search from.
  8699. * @return Next nearest power of two.
  8700. */
  8701. Tools.NearestPOT = function (x) {
  8702. var c = Tools.CeilingPOT(x);
  8703. var f = Tools.FloorPOT(x);
  8704. return (c - x) > (x - f) ? f : c;
  8705. };
  8706. Tools.GetExponentOfTwo = function (value, max, mode) {
  8707. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8708. var pot;
  8709. switch (mode) {
  8710. case BABYLON.Engine.SCALEMODE_FLOOR:
  8711. pot = Tools.FloorPOT(value);
  8712. break;
  8713. case BABYLON.Engine.SCALEMODE_NEAREST:
  8714. pot = Tools.NearestPOT(value);
  8715. break;
  8716. case BABYLON.Engine.SCALEMODE_CEILING:
  8717. default:
  8718. pot = Tools.CeilingPOT(value);
  8719. break;
  8720. }
  8721. return Math.min(pot, max);
  8722. };
  8723. Tools.GetFilename = function (path) {
  8724. var index = path.lastIndexOf("/");
  8725. if (index < 0)
  8726. return path;
  8727. return path.substring(index + 1);
  8728. };
  8729. /**
  8730. * Extracts the "folder" part of a path (everything before the filename).
  8731. * @param uri The URI to extract the info from
  8732. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8733. * @returns The "folder" part of the path
  8734. */
  8735. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8736. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8737. var index = uri.lastIndexOf("/");
  8738. if (index < 0) {
  8739. if (returnUnchangedIfNoSlash) {
  8740. return uri;
  8741. }
  8742. return "";
  8743. }
  8744. return uri.substring(0, index + 1);
  8745. };
  8746. Tools.GetDOMTextContent = function (element) {
  8747. var result = "";
  8748. var child = element.firstChild;
  8749. while (child) {
  8750. if (child.nodeType === 3) {
  8751. result += child.textContent;
  8752. }
  8753. child = child.nextSibling;
  8754. }
  8755. return result;
  8756. };
  8757. Tools.ToDegrees = function (angle) {
  8758. return angle * 180 / Math.PI;
  8759. };
  8760. Tools.ToRadians = function (angle) {
  8761. return angle * Math.PI / 180;
  8762. };
  8763. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8764. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8765. var output = "";
  8766. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8767. var i = 0;
  8768. var bytes = new Uint8Array(buffer);
  8769. while (i < bytes.length) {
  8770. chr1 = bytes[i++];
  8771. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8772. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8773. enc1 = chr1 >> 2;
  8774. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8775. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8776. enc4 = chr3 & 63;
  8777. if (isNaN(chr2)) {
  8778. enc3 = enc4 = 64;
  8779. }
  8780. else if (isNaN(chr3)) {
  8781. enc4 = 64;
  8782. }
  8783. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8784. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8785. }
  8786. return "data:image/png;base64," + output;
  8787. };
  8788. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8789. if (bias === void 0) { bias = null; }
  8790. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8791. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8792. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8793. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8794. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8795. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8796. }
  8797. if (bias) {
  8798. minimum.x -= minimum.x * bias.x + bias.y;
  8799. minimum.y -= minimum.y * bias.x + bias.y;
  8800. minimum.z -= minimum.z * bias.x + bias.y;
  8801. maximum.x += maximum.x * bias.x + bias.y;
  8802. maximum.y += maximum.y * bias.x + bias.y;
  8803. maximum.z += maximum.z * bias.x + bias.y;
  8804. }
  8805. return {
  8806. minimum: minimum,
  8807. maximum: maximum
  8808. };
  8809. };
  8810. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8811. if (bias === void 0) { bias = null; }
  8812. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8813. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8814. if (!stride) {
  8815. stride = 3;
  8816. }
  8817. for (var index = start; index < start + count; index++) {
  8818. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8819. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8820. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8821. }
  8822. if (bias) {
  8823. minimum.x -= minimum.x * bias.x + bias.y;
  8824. minimum.y -= minimum.y * bias.x + bias.y;
  8825. minimum.z -= minimum.z * bias.x + bias.y;
  8826. maximum.x += maximum.x * bias.x + bias.y;
  8827. maximum.y += maximum.y * bias.x + bias.y;
  8828. maximum.z += maximum.z * bias.x + bias.y;
  8829. }
  8830. return {
  8831. minimum: minimum,
  8832. maximum: maximum
  8833. };
  8834. };
  8835. Tools.Vector2ArrayFeeder = function (array) {
  8836. return function (index) {
  8837. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8838. var length = isFloatArray ? array.length / 2 : array.length;
  8839. if (index >= length) {
  8840. return null;
  8841. }
  8842. if (isFloatArray) {
  8843. var fa = array;
  8844. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8845. }
  8846. var a = array;
  8847. return a[index];
  8848. };
  8849. };
  8850. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8851. if (bias === void 0) { bias = null; }
  8852. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8853. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8854. var i = 0;
  8855. var cur = feeder(i++);
  8856. while (cur) {
  8857. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8858. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8859. cur = feeder(i++);
  8860. }
  8861. if (bias) {
  8862. minimum.x -= minimum.x * bias.x + bias.y;
  8863. minimum.y -= minimum.y * bias.x + bias.y;
  8864. maximum.x += maximum.x * bias.x + bias.y;
  8865. maximum.y += maximum.y * bias.x + bias.y;
  8866. }
  8867. return {
  8868. minimum: minimum,
  8869. maximum: maximum
  8870. };
  8871. };
  8872. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8873. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8874. return null;
  8875. return Array.isArray(obj) ? obj : [obj];
  8876. };
  8877. // Misc.
  8878. Tools.GetPointerPrefix = function () {
  8879. var eventPrefix = "pointer";
  8880. // Check if pointer events are supported
  8881. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8882. eventPrefix = "mouse";
  8883. }
  8884. return eventPrefix;
  8885. };
  8886. /**
  8887. * @param func - the function to be called
  8888. * @param requester - the object that will request the next frame. Falls back to window.
  8889. */
  8890. Tools.QueueNewFrame = function (func, requester) {
  8891. if (!Tools.IsWindowObjectExist()) {
  8892. return setTimeout(func, 16);
  8893. }
  8894. if (!requester) {
  8895. requester = window;
  8896. }
  8897. if (requester.requestAnimationFrame) {
  8898. return requester.requestAnimationFrame(func);
  8899. }
  8900. else if (requester.msRequestAnimationFrame) {
  8901. return requester.msRequestAnimationFrame(func);
  8902. }
  8903. else if (requester.webkitRequestAnimationFrame) {
  8904. return requester.webkitRequestAnimationFrame(func);
  8905. }
  8906. else if (requester.mozRequestAnimationFrame) {
  8907. return requester.mozRequestAnimationFrame(func);
  8908. }
  8909. else if (requester.oRequestAnimationFrame) {
  8910. return requester.oRequestAnimationFrame(func);
  8911. }
  8912. else {
  8913. return window.setTimeout(func, 16);
  8914. }
  8915. };
  8916. Tools.RequestFullscreen = function (element) {
  8917. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8918. if (!requestFunction)
  8919. return;
  8920. requestFunction.call(element);
  8921. };
  8922. Tools.ExitFullscreen = function () {
  8923. if (document.exitFullscreen) {
  8924. document.exitFullscreen();
  8925. }
  8926. else if (document.mozCancelFullScreen) {
  8927. document.mozCancelFullScreen();
  8928. }
  8929. else if (document.webkitCancelFullScreen) {
  8930. document.webkitCancelFullScreen();
  8931. }
  8932. else if (document.msCancelFullScreen) {
  8933. document.msCancelFullScreen();
  8934. }
  8935. };
  8936. Tools.SetCorsBehavior = function (url, element) {
  8937. if (url && url.indexOf("data:") === 0) {
  8938. return;
  8939. }
  8940. if (Tools.CorsBehavior) {
  8941. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8942. element.crossOrigin = Tools.CorsBehavior;
  8943. }
  8944. else {
  8945. var result = Tools.CorsBehavior(url);
  8946. if (result) {
  8947. element.crossOrigin = result;
  8948. }
  8949. }
  8950. }
  8951. };
  8952. // External files
  8953. Tools.CleanUrl = function (url) {
  8954. url = url.replace(/#/mg, "%23");
  8955. return url;
  8956. };
  8957. /**
  8958. * Loads an image as an HTMLImageElement.
  8959. * @param input url string, ArrayBuffer, or Blob to load
  8960. * @param onLoad callback called when the image successfully loads
  8961. * @param onError callback called when the image fails to load
  8962. * @param database database for caching
  8963. * @returns the HTMLImageElement of the loaded image
  8964. */
  8965. Tools.LoadImage = function (input, onLoad, onError, database) {
  8966. var url;
  8967. var usingObjectURL = false;
  8968. if (input instanceof ArrayBuffer) {
  8969. url = URL.createObjectURL(new Blob([input]));
  8970. usingObjectURL = true;
  8971. }
  8972. else if (input instanceof Blob) {
  8973. url = URL.createObjectURL(input);
  8974. usingObjectURL = true;
  8975. }
  8976. else {
  8977. url = Tools.CleanUrl(input);
  8978. url = Tools.PreprocessUrl(input);
  8979. }
  8980. var img = new Image();
  8981. Tools.SetCorsBehavior(url, img);
  8982. var loadHandler = function () {
  8983. if (usingObjectURL && img.src) {
  8984. URL.revokeObjectURL(img.src);
  8985. }
  8986. img.removeEventListener("load", loadHandler);
  8987. img.removeEventListener("error", errorHandler);
  8988. onLoad(img);
  8989. };
  8990. var errorHandler = function (err) {
  8991. if (usingObjectURL && img.src) {
  8992. URL.revokeObjectURL(img.src);
  8993. }
  8994. img.removeEventListener("load", loadHandler);
  8995. img.removeEventListener("error", errorHandler);
  8996. Tools.Error("Error while trying to load image: " + input);
  8997. if (onError) {
  8998. onError("Error while trying to load image: " + input, err);
  8999. }
  9000. };
  9001. img.addEventListener("load", loadHandler);
  9002. img.addEventListener("error", errorHandler);
  9003. var noIndexedDB = function () {
  9004. img.src = url;
  9005. };
  9006. var loadFromIndexedDB = function () {
  9007. if (database) {
  9008. database.loadImageFromDB(url, img);
  9009. }
  9010. };
  9011. //ANY database to do!
  9012. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9013. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9014. }
  9015. else {
  9016. if (url.indexOf("file:") !== -1) {
  9017. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9018. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9019. try {
  9020. var blobURL;
  9021. try {
  9022. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9023. }
  9024. catch (ex) {
  9025. // Chrome doesn't support oneTimeOnly parameter
  9026. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9027. }
  9028. img.src = blobURL;
  9029. usingObjectURL = true;
  9030. }
  9031. catch (e) {
  9032. img.src = "";
  9033. }
  9034. return img;
  9035. }
  9036. }
  9037. noIndexedDB();
  9038. }
  9039. return img;
  9040. };
  9041. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9042. url = Tools.CleanUrl(url);
  9043. url = Tools.PreprocessUrl(url);
  9044. // If file and file input are set
  9045. if (url.indexOf("file:") !== -1) {
  9046. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9047. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9048. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9049. }
  9050. }
  9051. var loadUrl = Tools.BaseUrl + url;
  9052. var aborted = false;
  9053. var fileRequest = {
  9054. onCompleteObservable: new BABYLON.Observable(),
  9055. abort: function () { return aborted = true; },
  9056. };
  9057. var requestFile = function () {
  9058. var request = new XMLHttpRequest();
  9059. var retryHandle = null;
  9060. fileRequest.abort = function () {
  9061. aborted = true;
  9062. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9063. request.abort();
  9064. }
  9065. if (retryHandle !== null) {
  9066. clearTimeout(retryHandle);
  9067. retryHandle = null;
  9068. }
  9069. };
  9070. var retryLoop = function (retryIndex) {
  9071. request.open('GET', loadUrl, true);
  9072. if (useArrayBuffer) {
  9073. request.responseType = "arraybuffer";
  9074. }
  9075. if (onProgress) {
  9076. request.addEventListener("progress", onProgress);
  9077. }
  9078. var onLoadEnd = function () {
  9079. request.removeEventListener("loadend", onLoadEnd);
  9080. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9081. fileRequest.onCompleteObservable.clear();
  9082. };
  9083. request.addEventListener("loadend", onLoadEnd);
  9084. var onReadyStateChange = function () {
  9085. if (aborted) {
  9086. return;
  9087. }
  9088. // In case of undefined state in some browsers.
  9089. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9090. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9091. request.removeEventListener("readystatechange", onReadyStateChange);
  9092. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9093. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9094. return;
  9095. }
  9096. var retryStrategy = Tools.DefaultRetryStrategy;
  9097. if (retryStrategy) {
  9098. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9099. if (waitTime !== -1) {
  9100. // Prevent the request from completing for retry.
  9101. request.removeEventListener("loadend", onLoadEnd);
  9102. request = new XMLHttpRequest();
  9103. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9104. return;
  9105. }
  9106. }
  9107. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9108. if (onError) {
  9109. onError(request, e);
  9110. }
  9111. else {
  9112. throw e;
  9113. }
  9114. }
  9115. };
  9116. request.addEventListener("readystatechange", onReadyStateChange);
  9117. request.send();
  9118. };
  9119. retryLoop(0);
  9120. };
  9121. // Caching all files
  9122. if (database && database.enableSceneOffline) {
  9123. var noIndexedDB_1 = function (request) {
  9124. if (request && request.status > 400) {
  9125. if (onError) {
  9126. onError(request);
  9127. }
  9128. }
  9129. else {
  9130. if (!aborted) {
  9131. requestFile();
  9132. }
  9133. }
  9134. };
  9135. var loadFromIndexedDB = function () {
  9136. // TODO: database needs to support aborting and should return a IFileRequest
  9137. if (aborted) {
  9138. return;
  9139. }
  9140. if (database) {
  9141. database.loadFileFromDB(url, function (data) {
  9142. if (!aborted) {
  9143. onSuccess(data);
  9144. }
  9145. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9146. }, onProgress ? function (event) {
  9147. if (!aborted) {
  9148. onProgress(event);
  9149. }
  9150. } : undefined, noIndexedDB_1, useArrayBuffer);
  9151. }
  9152. };
  9153. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9154. }
  9155. else {
  9156. requestFile();
  9157. }
  9158. return fileRequest;
  9159. };
  9160. /**
  9161. * Load a script (identified by an url). When the url returns, the
  9162. * content of this file is added into a new script element, attached to the DOM (body element)
  9163. */
  9164. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9165. var head = document.getElementsByTagName('head')[0];
  9166. var script = document.createElement('script');
  9167. script.type = 'text/javascript';
  9168. script.src = scriptUrl;
  9169. script.onload = function () {
  9170. if (onSuccess) {
  9171. onSuccess();
  9172. }
  9173. };
  9174. script.onerror = function (e) {
  9175. if (onError) {
  9176. onError("Unable to load script '" + scriptUrl + "'", e);
  9177. }
  9178. };
  9179. head.appendChild(script);
  9180. };
  9181. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9182. var reader = new FileReader();
  9183. var request = {
  9184. onCompleteObservable: new BABYLON.Observable(),
  9185. abort: function () { return reader.abort(); },
  9186. };
  9187. reader.onloadend = function (e) {
  9188. request.onCompleteObservable.notifyObservers(request);
  9189. };
  9190. reader.onload = function (e) {
  9191. //target doesn't have result from ts 1.3
  9192. callback(e.target['result']);
  9193. };
  9194. reader.onprogress = progressCallback;
  9195. reader.readAsDataURL(fileToLoad);
  9196. return request;
  9197. };
  9198. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9199. var reader = new FileReader();
  9200. var request = {
  9201. onCompleteObservable: new BABYLON.Observable(),
  9202. abort: function () { return reader.abort(); },
  9203. };
  9204. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9205. reader.onerror = function (e) {
  9206. Tools.Log("Error while reading file: " + fileToLoad.name);
  9207. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9208. };
  9209. reader.onload = function (e) {
  9210. //target doesn't have result from ts 1.3
  9211. callback(e.target['result']);
  9212. };
  9213. if (progressCallBack) {
  9214. reader.onprogress = progressCallBack;
  9215. }
  9216. if (!useArrayBuffer) {
  9217. // Asynchronous read
  9218. reader.readAsText(fileToLoad);
  9219. }
  9220. else {
  9221. reader.readAsArrayBuffer(fileToLoad);
  9222. }
  9223. return request;
  9224. };
  9225. //returns a downloadable url to a file content.
  9226. Tools.FileAsURL = function (content) {
  9227. var fileBlob = new Blob([content]);
  9228. var url = window.URL || window.webkitURL;
  9229. var link = url.createObjectURL(fileBlob);
  9230. return link;
  9231. };
  9232. // Misc.
  9233. Tools.Format = function (value, decimals) {
  9234. if (decimals === void 0) { decimals = 2; }
  9235. return value.toFixed(decimals);
  9236. };
  9237. Tools.CheckExtends = function (v, min, max) {
  9238. if (v.x < min.x)
  9239. min.x = v.x;
  9240. if (v.y < min.y)
  9241. min.y = v.y;
  9242. if (v.z < min.z)
  9243. min.z = v.z;
  9244. if (v.x > max.x)
  9245. max.x = v.x;
  9246. if (v.y > max.y)
  9247. max.y = v.y;
  9248. if (v.z > max.z)
  9249. max.z = v.z;
  9250. };
  9251. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9252. for (var prop in source) {
  9253. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9254. continue;
  9255. }
  9256. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9257. continue;
  9258. }
  9259. var sourceValue = source[prop];
  9260. var typeOfSourceValue = typeof sourceValue;
  9261. if (typeOfSourceValue === "function") {
  9262. continue;
  9263. }
  9264. try {
  9265. if (typeOfSourceValue === "object") {
  9266. if (sourceValue instanceof Array) {
  9267. destination[prop] = [];
  9268. if (sourceValue.length > 0) {
  9269. if (typeof sourceValue[0] == "object") {
  9270. for (var index = 0; index < sourceValue.length; index++) {
  9271. var clonedValue = cloneValue(sourceValue[index], destination);
  9272. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9273. destination[prop].push(clonedValue);
  9274. }
  9275. }
  9276. }
  9277. else {
  9278. destination[prop] = sourceValue.slice(0);
  9279. }
  9280. }
  9281. }
  9282. else {
  9283. destination[prop] = cloneValue(sourceValue, destination);
  9284. }
  9285. }
  9286. else {
  9287. destination[prop] = sourceValue;
  9288. }
  9289. }
  9290. catch (e) {
  9291. // Just ignore error (it could be because of a read-only property)
  9292. }
  9293. }
  9294. };
  9295. Tools.IsEmpty = function (obj) {
  9296. for (var i in obj) {
  9297. if (obj.hasOwnProperty(i)) {
  9298. return false;
  9299. }
  9300. }
  9301. return true;
  9302. };
  9303. Tools.RegisterTopRootEvents = function (events) {
  9304. for (var index = 0; index < events.length; index++) {
  9305. var event = events[index];
  9306. window.addEventListener(event.name, event.handler, false);
  9307. try {
  9308. if (window.parent) {
  9309. window.parent.addEventListener(event.name, event.handler, false);
  9310. }
  9311. }
  9312. catch (e) {
  9313. // Silently fails...
  9314. }
  9315. }
  9316. };
  9317. Tools.UnregisterTopRootEvents = function (events) {
  9318. for (var index = 0; index < events.length; index++) {
  9319. var event = events[index];
  9320. window.removeEventListener(event.name, event.handler);
  9321. try {
  9322. if (window.parent) {
  9323. window.parent.removeEventListener(event.name, event.handler);
  9324. }
  9325. }
  9326. catch (e) {
  9327. // Silently fails...
  9328. }
  9329. }
  9330. };
  9331. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9332. if (mimeType === void 0) { mimeType = "image/png"; }
  9333. // Read the contents of the framebuffer
  9334. var numberOfChannelsByLine = width * 4;
  9335. var halfHeight = height / 2;
  9336. //Reading datas from WebGL
  9337. var data = engine.readPixels(0, 0, width, height);
  9338. //To flip image on Y axis.
  9339. for (var i = 0; i < halfHeight; i++) {
  9340. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9341. var currentCell = j + i * numberOfChannelsByLine;
  9342. var targetLine = height - i - 1;
  9343. var targetCell = j + targetLine * numberOfChannelsByLine;
  9344. var temp = data[currentCell];
  9345. data[currentCell] = data[targetCell];
  9346. data[targetCell] = temp;
  9347. }
  9348. }
  9349. // Create a 2D canvas to store the result
  9350. if (!screenshotCanvas) {
  9351. screenshotCanvas = document.createElement('canvas');
  9352. }
  9353. screenshotCanvas.width = width;
  9354. screenshotCanvas.height = height;
  9355. var context = screenshotCanvas.getContext('2d');
  9356. if (context) {
  9357. // Copy the pixels to a 2D canvas
  9358. var imageData = context.createImageData(width, height);
  9359. var castData = (imageData.data);
  9360. castData.set(data);
  9361. context.putImageData(imageData, 0, 0);
  9362. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9363. }
  9364. };
  9365. /**
  9366. * Converts the canvas data to blob.
  9367. * This acts as a polyfill for browsers not supporting the to blob function.
  9368. * @param canvas Defines the canvas to extract the data from
  9369. * @param successCallback Defines the callback triggered once the data are available
  9370. * @param mimeType Defines the mime type of the result
  9371. */
  9372. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9373. if (mimeType === void 0) { mimeType = "image/png"; }
  9374. // We need HTMLCanvasElement.toBlob for HD screenshots
  9375. if (!canvas.toBlob) {
  9376. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9377. canvas.toBlob = function (callback, type, quality) {
  9378. var _this = this;
  9379. setTimeout(function () {
  9380. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9381. for (var i = 0; i < len; i++) {
  9382. arr[i] = binStr.charCodeAt(i);
  9383. }
  9384. callback(new Blob([arr]));
  9385. });
  9386. };
  9387. }
  9388. canvas.toBlob(function (blob) {
  9389. successCallback(blob);
  9390. }, mimeType);
  9391. };
  9392. /**
  9393. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9394. * @param successCallback Defines the callback triggered once the data are available
  9395. * @param mimeType Defines the mime type of the result
  9396. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9397. */
  9398. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9399. if (mimeType === void 0) { mimeType = "image/png"; }
  9400. if (successCallback) {
  9401. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9402. successCallback(base64Image);
  9403. }
  9404. else {
  9405. this.ToBlob(screenshotCanvas, function (blob) {
  9406. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9407. if (("download" in document.createElement("a"))) {
  9408. if (!fileName) {
  9409. var date = new Date();
  9410. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9411. fileName = "screenshot_" + stringDate + ".png";
  9412. }
  9413. Tools.Download(blob, fileName);
  9414. }
  9415. else {
  9416. var url = URL.createObjectURL(blob);
  9417. var newWindow = window.open("");
  9418. if (!newWindow)
  9419. return;
  9420. var img = newWindow.document.createElement("img");
  9421. img.onload = function () {
  9422. // no longer need to read the blob so it's revoked
  9423. URL.revokeObjectURL(url);
  9424. };
  9425. img.src = url;
  9426. newWindow.document.body.appendChild(img);
  9427. }
  9428. }, mimeType);
  9429. }
  9430. };
  9431. /**
  9432. * Downloads a blob in the browser
  9433. * @param blob defines the blob to download
  9434. * @param fileName defines the name of the downloaded file
  9435. */
  9436. Tools.Download = function (blob, fileName) {
  9437. if (navigator && navigator.msSaveBlob) {
  9438. navigator.msSaveBlob(blob, fileName);
  9439. return;
  9440. }
  9441. var url = window.URL.createObjectURL(blob);
  9442. var a = document.createElement("a");
  9443. document.body.appendChild(a);
  9444. a.style.display = "none";
  9445. a.href = url;
  9446. a.download = fileName;
  9447. a.addEventListener("click", function () {
  9448. if (a.parentElement) {
  9449. a.parentElement.removeChild(a);
  9450. }
  9451. });
  9452. a.click();
  9453. window.URL.revokeObjectURL(url);
  9454. };
  9455. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9456. if (mimeType === void 0) { mimeType = "image/png"; }
  9457. var width;
  9458. var height;
  9459. // If a precision value is specified
  9460. if (size.precision) {
  9461. width = Math.round(engine.getRenderWidth() * size.precision);
  9462. height = Math.round(width / engine.getAspectRatio(camera));
  9463. }
  9464. else if (size.width && size.height) {
  9465. width = size.width;
  9466. height = size.height;
  9467. }
  9468. //If passing only width, computing height to keep display canvas ratio.
  9469. else if (size.width && !size.height) {
  9470. width = size.width;
  9471. height = Math.round(width / engine.getAspectRatio(camera));
  9472. }
  9473. //If passing only height, computing width to keep display canvas ratio.
  9474. else if (size.height && !size.width) {
  9475. height = size.height;
  9476. width = Math.round(height * engine.getAspectRatio(camera));
  9477. }
  9478. //Assuming here that "size" parameter is a number
  9479. else if (!isNaN(size)) {
  9480. height = size;
  9481. width = size;
  9482. }
  9483. else {
  9484. Tools.Error("Invalid 'size' parameter !");
  9485. return;
  9486. }
  9487. if (!screenshotCanvas) {
  9488. screenshotCanvas = document.createElement('canvas');
  9489. }
  9490. screenshotCanvas.width = width;
  9491. screenshotCanvas.height = height;
  9492. var renderContext = screenshotCanvas.getContext("2d");
  9493. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9494. var newWidth = width;
  9495. var newHeight = newWidth / ratio;
  9496. if (newHeight > height) {
  9497. newHeight = height;
  9498. newWidth = newHeight * ratio;
  9499. }
  9500. var offsetX = Math.max(0, width - newWidth) / 2;
  9501. var offsetY = Math.max(0, height - newHeight) / 2;
  9502. var renderingCanvas = engine.getRenderingCanvas();
  9503. if (renderContext && renderingCanvas) {
  9504. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9505. }
  9506. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9507. };
  9508. /**
  9509. * Generates an image screenshot from the specified camera.
  9510. *
  9511. * @param engine The engine to use for rendering
  9512. * @param camera The camera to use for rendering
  9513. * @param size This parameter can be set to a single number or to an object with the
  9514. * following (optional) properties: precision, width, height. If a single number is passed,
  9515. * it will be used for both width and height. If an object is passed, the screenshot size
  9516. * will be derived from the parameters. The precision property is a multiplier allowing
  9517. * rendering at a higher or lower resolution.
  9518. * @param successCallback The callback receives a single parameter which contains the
  9519. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9520. * src parameter of an <img> to display it.
  9521. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9522. * Check your browser for supported MIME types.
  9523. * @param samples Texture samples (default: 1)
  9524. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9525. * @param fileName A name for for the downloaded file.
  9526. * @constructor
  9527. */
  9528. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9529. if (mimeType === void 0) { mimeType = "image/png"; }
  9530. if (samples === void 0) { samples = 1; }
  9531. if (antialiasing === void 0) { antialiasing = false; }
  9532. var width;
  9533. var height;
  9534. //If a precision value is specified
  9535. if (size.precision) {
  9536. width = Math.round(engine.getRenderWidth() * size.precision);
  9537. height = Math.round(width / engine.getAspectRatio(camera));
  9538. size = { width: width, height: height };
  9539. }
  9540. else if (size.width && size.height) {
  9541. width = size.width;
  9542. height = size.height;
  9543. }
  9544. //If passing only width, computing height to keep display canvas ratio.
  9545. else if (size.width && !size.height) {
  9546. width = size.width;
  9547. height = Math.round(width / engine.getAspectRatio(camera));
  9548. size = { width: width, height: height };
  9549. }
  9550. //If passing only height, computing width to keep display canvas ratio.
  9551. else if (size.height && !size.width) {
  9552. height = size.height;
  9553. width = Math.round(height * engine.getAspectRatio(camera));
  9554. size = { width: width, height: height };
  9555. }
  9556. //Assuming here that "size" parameter is a number
  9557. else if (!isNaN(size)) {
  9558. height = size;
  9559. width = size;
  9560. }
  9561. else {
  9562. Tools.Error("Invalid 'size' parameter !");
  9563. return;
  9564. }
  9565. var scene = camera.getScene();
  9566. var previousCamera = null;
  9567. if (scene.activeCamera !== camera) {
  9568. previousCamera = scene.activeCamera;
  9569. scene.activeCamera = camera;
  9570. }
  9571. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9572. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9573. texture.renderList = null;
  9574. texture.samples = samples;
  9575. if (antialiasing) {
  9576. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9577. }
  9578. texture.onAfterRenderObservable.add(function () {
  9579. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9580. });
  9581. scene.incrementRenderId();
  9582. scene.resetCachedMaterial();
  9583. texture.render(true);
  9584. texture.dispose();
  9585. if (previousCamera) {
  9586. scene.activeCamera = previousCamera;
  9587. }
  9588. camera.getProjectionMatrix(true); // Force cache refresh;
  9589. };
  9590. // XHR response validator for local file scenario
  9591. Tools.ValidateXHRData = function (xhr, dataType) {
  9592. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9593. if (dataType === void 0) { dataType = 7; }
  9594. try {
  9595. if (dataType & 1) {
  9596. if (xhr.responseText && xhr.responseText.length > 0) {
  9597. return true;
  9598. }
  9599. else if (dataType === 1) {
  9600. return false;
  9601. }
  9602. }
  9603. if (dataType & 2) {
  9604. // Check header width and height since there is no "TGA" magic number
  9605. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9606. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9607. return true;
  9608. }
  9609. else if (dataType === 2) {
  9610. return false;
  9611. }
  9612. }
  9613. if (dataType & 4) {
  9614. // Check for the "DDS" magic number
  9615. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9616. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9617. return true;
  9618. }
  9619. else {
  9620. return false;
  9621. }
  9622. }
  9623. }
  9624. catch (e) {
  9625. // Global protection
  9626. }
  9627. return false;
  9628. };
  9629. /**
  9630. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9631. * Be aware Math.random() could cause collisions, but:
  9632. * "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"
  9633. */
  9634. Tools.RandomId = function () {
  9635. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9636. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9637. return v.toString(16);
  9638. });
  9639. };
  9640. /**
  9641. * Test if the given uri is a base64 string.
  9642. * @param uri The uri to test
  9643. * @return True if the uri is a base64 string or false otherwise.
  9644. */
  9645. Tools.IsBase64 = function (uri) {
  9646. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9647. };
  9648. /**
  9649. * Decode the given base64 uri.
  9650. * @param uri The uri to decode
  9651. * @return The decoded base64 data.
  9652. */
  9653. Tools.DecodeBase64 = function (uri) {
  9654. var decodedString = atob(uri.split(",")[1]);
  9655. var bufferLength = decodedString.length;
  9656. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9657. for (var i = 0; i < bufferLength; i++) {
  9658. bufferView[i] = decodedString.charCodeAt(i);
  9659. }
  9660. return bufferView.buffer;
  9661. };
  9662. Object.defineProperty(Tools, "NoneLogLevel", {
  9663. get: function () {
  9664. return Tools._NoneLogLevel;
  9665. },
  9666. enumerable: true,
  9667. configurable: true
  9668. });
  9669. Object.defineProperty(Tools, "MessageLogLevel", {
  9670. get: function () {
  9671. return Tools._MessageLogLevel;
  9672. },
  9673. enumerable: true,
  9674. configurable: true
  9675. });
  9676. Object.defineProperty(Tools, "WarningLogLevel", {
  9677. get: function () {
  9678. return Tools._WarningLogLevel;
  9679. },
  9680. enumerable: true,
  9681. configurable: true
  9682. });
  9683. Object.defineProperty(Tools, "ErrorLogLevel", {
  9684. get: function () {
  9685. return Tools._ErrorLogLevel;
  9686. },
  9687. enumerable: true,
  9688. configurable: true
  9689. });
  9690. Object.defineProperty(Tools, "AllLogLevel", {
  9691. get: function () {
  9692. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9693. },
  9694. enumerable: true,
  9695. configurable: true
  9696. });
  9697. Tools._AddLogEntry = function (entry) {
  9698. Tools._LogCache = entry + Tools._LogCache;
  9699. if (Tools.OnNewCacheEntry) {
  9700. Tools.OnNewCacheEntry(entry);
  9701. }
  9702. };
  9703. Tools._FormatMessage = function (message) {
  9704. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9705. var date = new Date();
  9706. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9707. };
  9708. Tools._LogDisabled = function (message) {
  9709. // nothing to do
  9710. };
  9711. Tools._LogEnabled = function (message) {
  9712. var formattedMessage = Tools._FormatMessage(message);
  9713. console.log("BJS - " + formattedMessage);
  9714. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9715. Tools._AddLogEntry(entry);
  9716. };
  9717. Tools._WarnDisabled = function (message) {
  9718. // nothing to do
  9719. };
  9720. Tools._WarnEnabled = function (message) {
  9721. var formattedMessage = Tools._FormatMessage(message);
  9722. console.warn("BJS - " + formattedMessage);
  9723. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9724. Tools._AddLogEntry(entry);
  9725. };
  9726. Tools._ErrorDisabled = function (message) {
  9727. // nothing to do
  9728. };
  9729. Tools._ErrorEnabled = function (message) {
  9730. Tools.errorsCount++;
  9731. var formattedMessage = Tools._FormatMessage(message);
  9732. console.error("BJS - " + formattedMessage);
  9733. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9734. Tools._AddLogEntry(entry);
  9735. };
  9736. Object.defineProperty(Tools, "LogCache", {
  9737. get: function () {
  9738. return Tools._LogCache;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Tools.ClearLogCache = function () {
  9744. Tools._LogCache = "";
  9745. Tools.errorsCount = 0;
  9746. };
  9747. Object.defineProperty(Tools, "LogLevels", {
  9748. set: function (level) {
  9749. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9750. Tools.Log = Tools._LogEnabled;
  9751. }
  9752. else {
  9753. Tools.Log = Tools._LogDisabled;
  9754. }
  9755. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9756. Tools.Warn = Tools._WarnEnabled;
  9757. }
  9758. else {
  9759. Tools.Warn = Tools._WarnDisabled;
  9760. }
  9761. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9762. Tools.Error = Tools._ErrorEnabled;
  9763. }
  9764. else {
  9765. Tools.Error = Tools._ErrorDisabled;
  9766. }
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Tools.IsWindowObjectExist = function () {
  9772. return (typeof window) !== "undefined";
  9773. };
  9774. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9775. get: function () {
  9776. return Tools._PerformanceNoneLogLevel;
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9782. get: function () {
  9783. return Tools._PerformanceUserMarkLogLevel;
  9784. },
  9785. enumerable: true,
  9786. configurable: true
  9787. });
  9788. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9789. get: function () {
  9790. return Tools._PerformanceConsoleLogLevel;
  9791. },
  9792. enumerable: true,
  9793. configurable: true
  9794. });
  9795. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9796. set: function (level) {
  9797. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9798. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9799. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9800. return;
  9801. }
  9802. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9803. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9804. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9805. return;
  9806. }
  9807. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9808. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9814. };
  9815. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9816. };
  9817. Tools._StartUserMark = function (counterName, condition) {
  9818. if (condition === void 0) { condition = true; }
  9819. if (!Tools._performance) {
  9820. if (!Tools.IsWindowObjectExist()) {
  9821. return;
  9822. }
  9823. Tools._performance = window.performance;
  9824. }
  9825. if (!condition || !Tools._performance.mark) {
  9826. return;
  9827. }
  9828. Tools._performance.mark(counterName + "-Begin");
  9829. };
  9830. Tools._EndUserMark = function (counterName, condition) {
  9831. if (condition === void 0) { condition = true; }
  9832. if (!condition || !Tools._performance.mark) {
  9833. return;
  9834. }
  9835. Tools._performance.mark(counterName + "-End");
  9836. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9837. };
  9838. Tools._StartPerformanceConsole = function (counterName, condition) {
  9839. if (condition === void 0) { condition = true; }
  9840. if (!condition) {
  9841. return;
  9842. }
  9843. Tools._StartUserMark(counterName, condition);
  9844. if (console.time) {
  9845. console.time(counterName);
  9846. }
  9847. };
  9848. Tools._EndPerformanceConsole = function (counterName, condition) {
  9849. if (condition === void 0) { condition = true; }
  9850. if (!condition) {
  9851. return;
  9852. }
  9853. Tools._EndUserMark(counterName, condition);
  9854. if (console.time) {
  9855. console.timeEnd(counterName);
  9856. }
  9857. };
  9858. Object.defineProperty(Tools, "Now", {
  9859. get: function () {
  9860. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9861. return window.performance.now();
  9862. }
  9863. return Date.now();
  9864. },
  9865. enumerable: true,
  9866. configurable: true
  9867. });
  9868. /**
  9869. * This method will return the name of the class used to create the instance of the given object.
  9870. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9871. * @param object the object to get the class name from
  9872. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9873. */
  9874. Tools.GetClassName = function (object, isType) {
  9875. if (isType === void 0) { isType = false; }
  9876. var name = null;
  9877. if (!isType && object.getClassName) {
  9878. name = object.getClassName();
  9879. }
  9880. else {
  9881. if (object instanceof Object) {
  9882. var classObj = isType ? object : Object.getPrototypeOf(object);
  9883. name = classObj.constructor["__bjsclassName__"];
  9884. }
  9885. if (!name) {
  9886. name = typeof object;
  9887. }
  9888. }
  9889. return name;
  9890. };
  9891. Tools.First = function (array, predicate) {
  9892. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9893. var el = array_1[_i];
  9894. if (predicate(el)) {
  9895. return el;
  9896. }
  9897. }
  9898. return null;
  9899. };
  9900. /**
  9901. * This method will return the name of the full name of the class, including its owning module (if any).
  9902. * 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).
  9903. * @param object the object to get the class name from
  9904. * @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.
  9905. */
  9906. Tools.getFullClassName = function (object, isType) {
  9907. if (isType === void 0) { isType = false; }
  9908. var className = null;
  9909. var moduleName = null;
  9910. if (!isType && object.getClassName) {
  9911. className = object.getClassName();
  9912. }
  9913. else {
  9914. if (object instanceof Object) {
  9915. var classObj = isType ? object : Object.getPrototypeOf(object);
  9916. className = classObj.constructor["__bjsclassName__"];
  9917. moduleName = classObj.constructor["__bjsmoduleName__"];
  9918. }
  9919. if (!className) {
  9920. className = typeof object;
  9921. }
  9922. }
  9923. if (!className) {
  9924. return null;
  9925. }
  9926. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9927. };
  9928. /**
  9929. * 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.
  9930. * @param array
  9931. */
  9932. Tools.arrayOrStringFeeder = function (array) {
  9933. return function (index) {
  9934. if (index >= array.length) {
  9935. return null;
  9936. }
  9937. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9938. if (val && val.getHashCode) {
  9939. val = val.getHashCode();
  9940. }
  9941. if (typeof val === "string") {
  9942. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9943. }
  9944. return val;
  9945. };
  9946. };
  9947. /**
  9948. * Compute the hashCode of a stream of number
  9949. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9950. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9951. * @return the hash code computed
  9952. */
  9953. Tools.hashCodeFromStream = function (feeder) {
  9954. // Based from here: http://stackoverflow.com/a/7616484/802124
  9955. var hash = 0;
  9956. var index = 0;
  9957. var chr = feeder(index++);
  9958. while (chr != null) {
  9959. hash = ((hash << 5) - hash) + chr;
  9960. hash |= 0; // Convert to 32bit integer
  9961. chr = feeder(index++);
  9962. }
  9963. return hash;
  9964. };
  9965. /**
  9966. * Returns a promise that resolves after the given amount of time.
  9967. * @param delay Number of milliseconds to delay
  9968. * @returns Promise that resolves after the given amount of time
  9969. */
  9970. Tools.DelayAsync = function (delay) {
  9971. return new Promise(function (resolve) {
  9972. setTimeout(function () {
  9973. resolve();
  9974. }, delay);
  9975. });
  9976. };
  9977. /**
  9978. * Gets the current gradient from an array of IValueGradient
  9979. * @param ratio defines the current ratio to get
  9980. * @param gradients defines the array of IValueGradient
  9981. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9982. */
  9983. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9984. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9985. var currentGradient = gradients[gradientIndex];
  9986. var nextGradient = gradients[gradientIndex + 1];
  9987. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9988. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9989. updateFunc(currentGradient, nextGradient, scale);
  9990. }
  9991. }
  9992. };
  9993. Tools.BaseUrl = "";
  9994. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9995. /**
  9996. * Default behaviour for cors in the application.
  9997. * It can be a string if the expected behavior is identical in the entire app.
  9998. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9999. */
  10000. Tools.CorsBehavior = "anonymous";
  10001. Tools.UseFallbackTexture = true;
  10002. /**
  10003. * Use this object to register external classes like custom textures or material
  10004. * to allow the laoders to instantiate them
  10005. */
  10006. Tools.RegisteredExternalClasses = {};
  10007. // Used in case of a texture loading problem
  10008. 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";
  10009. Tools._tmpFloatArray = new Float32Array(1);
  10010. Tools.PreprocessUrl = function (url) {
  10011. return url;
  10012. };
  10013. // Logs
  10014. Tools._NoneLogLevel = 0;
  10015. Tools._MessageLogLevel = 1;
  10016. Tools._WarningLogLevel = 2;
  10017. Tools._ErrorLogLevel = 4;
  10018. Tools._LogCache = "";
  10019. Tools.errorsCount = 0;
  10020. Tools.Log = Tools._LogEnabled;
  10021. Tools.Warn = Tools._WarnEnabled;
  10022. Tools.Error = Tools._ErrorEnabled;
  10023. // Performances
  10024. Tools._PerformanceNoneLogLevel = 0;
  10025. Tools._PerformanceUserMarkLogLevel = 1;
  10026. Tools._PerformanceConsoleLogLevel = 2;
  10027. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10028. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10029. return Tools;
  10030. }());
  10031. BABYLON.Tools = Tools;
  10032. /**
  10033. * This class is used to track a performance counter which is number based.
  10034. * The user has access to many properties which give statistics of different nature
  10035. *
  10036. * The implementer can track two kinds of Performance Counter: time and count
  10037. * 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.
  10038. * 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.
  10039. */
  10040. var PerfCounter = /** @class */ (function () {
  10041. function PerfCounter() {
  10042. this._startMonitoringTime = 0;
  10043. this._min = 0;
  10044. this._max = 0;
  10045. this._average = 0;
  10046. this._lastSecAverage = 0;
  10047. this._current = 0;
  10048. this._totalValueCount = 0;
  10049. this._totalAccumulated = 0;
  10050. this._lastSecAccumulated = 0;
  10051. this._lastSecTime = 0;
  10052. this._lastSecValueCount = 0;
  10053. }
  10054. Object.defineProperty(PerfCounter.prototype, "min", {
  10055. /**
  10056. * Returns the smallest value ever
  10057. */
  10058. get: function () {
  10059. return this._min;
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(PerfCounter.prototype, "max", {
  10065. /**
  10066. * Returns the biggest value ever
  10067. */
  10068. get: function () {
  10069. return this._max;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(PerfCounter.prototype, "average", {
  10075. /**
  10076. * Returns the average value since the performance counter is running
  10077. */
  10078. get: function () {
  10079. return this._average;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10085. /**
  10086. * Returns the average value of the last second the counter was monitored
  10087. */
  10088. get: function () {
  10089. return this._lastSecAverage;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(PerfCounter.prototype, "current", {
  10095. /**
  10096. * Returns the current value
  10097. */
  10098. get: function () {
  10099. return this._current;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(PerfCounter.prototype, "total", {
  10105. get: function () {
  10106. return this._totalAccumulated;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(PerfCounter.prototype, "count", {
  10112. get: function () {
  10113. return this._totalValueCount;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. /**
  10119. * Call this method to start monitoring a new frame.
  10120. * 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.
  10121. */
  10122. PerfCounter.prototype.fetchNewFrame = function () {
  10123. this._totalValueCount++;
  10124. this._current = 0;
  10125. this._lastSecValueCount++;
  10126. };
  10127. /**
  10128. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10129. * @param newCount the count value to add to the monitored count
  10130. * @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.
  10131. */
  10132. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10133. if (!PerfCounter.Enabled) {
  10134. return;
  10135. }
  10136. this._current += newCount;
  10137. if (fetchResult) {
  10138. this._fetchResult();
  10139. }
  10140. };
  10141. /**
  10142. * Start monitoring this performance counter
  10143. */
  10144. PerfCounter.prototype.beginMonitoring = function () {
  10145. if (!PerfCounter.Enabled) {
  10146. return;
  10147. }
  10148. this._startMonitoringTime = Tools.Now;
  10149. };
  10150. /**
  10151. * Compute the time lapsed since the previous beginMonitoring() call.
  10152. * @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
  10153. */
  10154. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10155. if (newFrame === void 0) { newFrame = true; }
  10156. if (!PerfCounter.Enabled) {
  10157. return;
  10158. }
  10159. if (newFrame) {
  10160. this.fetchNewFrame();
  10161. }
  10162. var currentTime = Tools.Now;
  10163. this._current = currentTime - this._startMonitoringTime;
  10164. if (newFrame) {
  10165. this._fetchResult();
  10166. }
  10167. };
  10168. PerfCounter.prototype._fetchResult = function () {
  10169. this._totalAccumulated += this._current;
  10170. this._lastSecAccumulated += this._current;
  10171. // Min/Max update
  10172. this._min = Math.min(this._min, this._current);
  10173. this._max = Math.max(this._max, this._current);
  10174. this._average = this._totalAccumulated / this._totalValueCount;
  10175. // Reset last sec?
  10176. var now = Tools.Now;
  10177. if ((now - this._lastSecTime) > 1000) {
  10178. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10179. this._lastSecTime = now;
  10180. this._lastSecAccumulated = 0;
  10181. this._lastSecValueCount = 0;
  10182. }
  10183. };
  10184. PerfCounter.Enabled = true;
  10185. return PerfCounter;
  10186. }());
  10187. BABYLON.PerfCounter = PerfCounter;
  10188. /**
  10189. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10190. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10191. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10192. * @param name The name of the class, case should be preserved
  10193. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10194. */
  10195. function className(name, module) {
  10196. return function (target) {
  10197. target["__bjsclassName__"] = name;
  10198. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10199. };
  10200. }
  10201. BABYLON.className = className;
  10202. /**
  10203. * An implementation of a loop for asynchronous functions.
  10204. */
  10205. var AsyncLoop = /** @class */ (function () {
  10206. /**
  10207. * Constroctor.
  10208. * @param iterations the number of iterations.
  10209. * @param _fn the function to run each iteration
  10210. * @param _successCallback the callback that will be called upon succesful execution
  10211. * @param offset starting offset.
  10212. */
  10213. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10214. if (offset === void 0) { offset = 0; }
  10215. this.iterations = iterations;
  10216. this._fn = _fn;
  10217. this._successCallback = _successCallback;
  10218. this.index = offset - 1;
  10219. this._done = false;
  10220. }
  10221. /**
  10222. * Execute the next iteration. Must be called after the last iteration was finished.
  10223. */
  10224. AsyncLoop.prototype.executeNext = function () {
  10225. if (!this._done) {
  10226. if (this.index + 1 < this.iterations) {
  10227. ++this.index;
  10228. this._fn(this);
  10229. }
  10230. else {
  10231. this.breakLoop();
  10232. }
  10233. }
  10234. };
  10235. /**
  10236. * Break the loop and run the success callback.
  10237. */
  10238. AsyncLoop.prototype.breakLoop = function () {
  10239. this._done = true;
  10240. this._successCallback();
  10241. };
  10242. /**
  10243. * Helper function
  10244. */
  10245. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10246. if (offset === void 0) { offset = 0; }
  10247. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10248. loop.executeNext();
  10249. return loop;
  10250. };
  10251. /**
  10252. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10253. * @param iterations total number of iterations
  10254. * @param syncedIterations number of synchronous iterations in each async iteration.
  10255. * @param fn the function to call each iteration.
  10256. * @param callback a success call back that will be called when iterating stops.
  10257. * @param breakFunction a break condition (optional)
  10258. * @param timeout timeout settings for the setTimeout function. default - 0.
  10259. * @constructor
  10260. */
  10261. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10262. if (timeout === void 0) { timeout = 0; }
  10263. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10264. if (breakFunction && breakFunction())
  10265. loop.breakLoop();
  10266. else {
  10267. setTimeout(function () {
  10268. for (var i = 0; i < syncedIterations; ++i) {
  10269. var iteration = (loop.index * syncedIterations) + i;
  10270. if (iteration >= iterations)
  10271. break;
  10272. fn(iteration);
  10273. if (breakFunction && breakFunction()) {
  10274. loop.breakLoop();
  10275. break;
  10276. }
  10277. }
  10278. loop.executeNext();
  10279. }, timeout);
  10280. }
  10281. }, callback);
  10282. };
  10283. return AsyncLoop;
  10284. }());
  10285. BABYLON.AsyncLoop = AsyncLoop;
  10286. })(BABYLON || (BABYLON = {}));
  10287. //# sourceMappingURL=babylon.tools.js.map
  10288. var BABYLON;
  10289. (function (BABYLON) {
  10290. var PromiseStates;
  10291. (function (PromiseStates) {
  10292. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10293. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10294. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10295. })(PromiseStates || (PromiseStates = {}));
  10296. var FulFillmentAgregator = /** @class */ (function () {
  10297. function FulFillmentAgregator() {
  10298. this.count = 0;
  10299. this.target = 0;
  10300. this.results = [];
  10301. }
  10302. return FulFillmentAgregator;
  10303. }());
  10304. var InternalPromise = /** @class */ (function () {
  10305. function InternalPromise(resolver) {
  10306. var _this = this;
  10307. this._state = PromiseStates.Pending;
  10308. this._children = new Array();
  10309. this._rejectWasConsumed = false;
  10310. if (!resolver) {
  10311. return;
  10312. }
  10313. try {
  10314. resolver(function (value) {
  10315. _this._resolve(value);
  10316. }, function (reason) {
  10317. _this._reject(reason);
  10318. });
  10319. }
  10320. catch (e) {
  10321. this._reject(e);
  10322. }
  10323. }
  10324. Object.defineProperty(InternalPromise.prototype, "_result", {
  10325. get: function () {
  10326. return this._resultValue;
  10327. },
  10328. set: function (value) {
  10329. this._resultValue = value;
  10330. if (this._parent && this._parent._result === undefined) {
  10331. this._parent._result = value;
  10332. }
  10333. },
  10334. enumerable: true,
  10335. configurable: true
  10336. });
  10337. InternalPromise.prototype.catch = function (onRejected) {
  10338. return this.then(undefined, onRejected);
  10339. };
  10340. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10341. var _this = this;
  10342. var newPromise = new InternalPromise();
  10343. newPromise._onFulfilled = onFulfilled;
  10344. newPromise._onRejected = onRejected;
  10345. // Composition
  10346. this._children.push(newPromise);
  10347. newPromise._parent = this;
  10348. if (this._state !== PromiseStates.Pending) {
  10349. BABYLON.Tools.SetImmediate(function () {
  10350. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10351. var returnedValue = newPromise._resolve(_this._result);
  10352. if (returnedValue !== undefined && returnedValue !== null) {
  10353. if (returnedValue._state !== undefined) {
  10354. var returnedPromise = returnedValue;
  10355. newPromise._children.push(returnedPromise);
  10356. returnedPromise._parent = newPromise;
  10357. newPromise = returnedPromise;
  10358. }
  10359. else {
  10360. newPromise._result = returnedValue;
  10361. }
  10362. }
  10363. }
  10364. else {
  10365. newPromise._reject(_this._reason);
  10366. }
  10367. });
  10368. }
  10369. return newPromise;
  10370. };
  10371. InternalPromise.prototype._moveChildren = function (children) {
  10372. var _this = this;
  10373. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10374. this._children.forEach(function (child) {
  10375. child._parent = _this;
  10376. });
  10377. if (this._state === PromiseStates.Fulfilled) {
  10378. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10379. var child = _b[_i];
  10380. child._resolve(this._result);
  10381. }
  10382. }
  10383. else if (this._state === PromiseStates.Rejected) {
  10384. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10385. var child = _d[_c];
  10386. child._reject(this._reason);
  10387. }
  10388. }
  10389. var _a;
  10390. };
  10391. InternalPromise.prototype._resolve = function (value) {
  10392. try {
  10393. this._state = PromiseStates.Fulfilled;
  10394. var returnedValue = null;
  10395. if (this._onFulfilled) {
  10396. returnedValue = this._onFulfilled(value);
  10397. }
  10398. if (returnedValue !== undefined && returnedValue !== null) {
  10399. if (returnedValue._state !== undefined) {
  10400. // Transmit children
  10401. var returnedPromise = returnedValue;
  10402. returnedPromise._parent = this;
  10403. returnedPromise._moveChildren(this._children);
  10404. value = returnedPromise._result;
  10405. }
  10406. else {
  10407. value = returnedValue;
  10408. }
  10409. }
  10410. this._result = value;
  10411. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10412. var child = _a[_i];
  10413. child._resolve(value);
  10414. }
  10415. this._children.length = 0;
  10416. delete this._onFulfilled;
  10417. delete this._onRejected;
  10418. }
  10419. catch (e) {
  10420. this._reject(e, true);
  10421. }
  10422. };
  10423. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10424. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10425. this._state = PromiseStates.Rejected;
  10426. this._reason = reason;
  10427. if (this._onRejected && !onLocalThrow) {
  10428. try {
  10429. this._onRejected(reason);
  10430. this._rejectWasConsumed = true;
  10431. }
  10432. catch (e) {
  10433. reason = e;
  10434. }
  10435. }
  10436. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10437. var child = _a[_i];
  10438. if (this._rejectWasConsumed) {
  10439. child._resolve(null);
  10440. }
  10441. else {
  10442. child._reject(reason);
  10443. }
  10444. }
  10445. this._children.length = 0;
  10446. delete this._onFulfilled;
  10447. delete this._onRejected;
  10448. };
  10449. InternalPromise.resolve = function (value) {
  10450. var newPromise = new InternalPromise();
  10451. newPromise._resolve(value);
  10452. return newPromise;
  10453. };
  10454. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10455. promise.then(function (value) {
  10456. agregator.results[index] = value;
  10457. agregator.count++;
  10458. if (agregator.count === agregator.target) {
  10459. agregator.rootPromise._resolve(agregator.results);
  10460. }
  10461. return null;
  10462. }, function (reason) {
  10463. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10464. agregator.rootPromise._reject(reason);
  10465. }
  10466. });
  10467. };
  10468. InternalPromise.all = function (promises) {
  10469. var newPromise = new InternalPromise();
  10470. var agregator = new FulFillmentAgregator();
  10471. agregator.target = promises.length;
  10472. agregator.rootPromise = newPromise;
  10473. if (promises.length) {
  10474. for (var index = 0; index < promises.length; index++) {
  10475. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10476. }
  10477. }
  10478. else {
  10479. newPromise._resolve([]);
  10480. }
  10481. return newPromise;
  10482. };
  10483. InternalPromise.race = function (promises) {
  10484. var newPromise = new InternalPromise();
  10485. if (promises.length) {
  10486. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10487. var promise = promises_1[_i];
  10488. promise.then(function (value) {
  10489. if (newPromise) {
  10490. newPromise._resolve(value);
  10491. newPromise = null;
  10492. }
  10493. return null;
  10494. }, function (reason) {
  10495. if (newPromise) {
  10496. newPromise._reject(reason);
  10497. newPromise = null;
  10498. }
  10499. });
  10500. }
  10501. }
  10502. return newPromise;
  10503. };
  10504. return InternalPromise;
  10505. }());
  10506. /**
  10507. * Helper class that provides a small promise polyfill
  10508. */
  10509. var PromisePolyfill = /** @class */ (function () {
  10510. function PromisePolyfill() {
  10511. }
  10512. /**
  10513. * Static function used to check if the polyfill is required
  10514. * If this is the case then the function will inject the polyfill to window.Promise
  10515. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10516. */
  10517. PromisePolyfill.Apply = function (force) {
  10518. if (force === void 0) { force = false; }
  10519. if (force || typeof Promise === 'undefined') {
  10520. var root = window;
  10521. root.Promise = InternalPromise;
  10522. }
  10523. };
  10524. return PromisePolyfill;
  10525. }());
  10526. BABYLON.PromisePolyfill = PromisePolyfill;
  10527. })(BABYLON || (BABYLON = {}));
  10528. //# sourceMappingURL=babylon.promise.js.map
  10529. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10530. var BABYLON;
  10531. (function (BABYLON) {
  10532. /**
  10533. * Helper class to push actions to a pool of workers.
  10534. */
  10535. var WorkerPool = /** @class */ (function () {
  10536. /**
  10537. * Constructor
  10538. * @param workers Array of workers to use for actions
  10539. */
  10540. function WorkerPool(workers) {
  10541. this._pendingActions = new Array();
  10542. this._workerInfos = workers.map(function (worker) { return ({
  10543. worker: worker,
  10544. active: false
  10545. }); });
  10546. }
  10547. /**
  10548. * Terminates all workers and clears any pending actions.
  10549. */
  10550. WorkerPool.prototype.dispose = function () {
  10551. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10552. var workerInfo = _a[_i];
  10553. workerInfo.worker.terminate();
  10554. }
  10555. delete this._workerInfos;
  10556. delete this._pendingActions;
  10557. };
  10558. /**
  10559. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10560. * pended until a worker has completed its action.
  10561. * @param action The action to perform. Call onComplete when the action is complete.
  10562. */
  10563. WorkerPool.prototype.push = function (action) {
  10564. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10565. var workerInfo = _a[_i];
  10566. if (!workerInfo.active) {
  10567. this._execute(workerInfo, action);
  10568. return;
  10569. }
  10570. }
  10571. this._pendingActions.push(action);
  10572. };
  10573. WorkerPool.prototype._execute = function (workerInfo, action) {
  10574. var _this = this;
  10575. workerInfo.active = true;
  10576. action(workerInfo.worker, function () {
  10577. workerInfo.active = false;
  10578. var nextAction = _this._pendingActions.shift();
  10579. if (nextAction) {
  10580. _this._execute(workerInfo, nextAction);
  10581. }
  10582. });
  10583. };
  10584. return WorkerPool;
  10585. }());
  10586. BABYLON.WorkerPool = WorkerPool;
  10587. })(BABYLON || (BABYLON = {}));
  10588. //# sourceMappingURL=babylon.workerPool.js.map
  10589. var BABYLON;
  10590. (function (BABYLON) {
  10591. /**
  10592. * @hidden
  10593. **/
  10594. var _AlphaState = /** @class */ (function () {
  10595. /**
  10596. * Initializes the state.
  10597. */
  10598. function _AlphaState() {
  10599. this._isAlphaBlendDirty = false;
  10600. this._isBlendFunctionParametersDirty = false;
  10601. this._isBlendEquationParametersDirty = false;
  10602. this._isBlendConstantsDirty = false;
  10603. this._alphaBlend = false;
  10604. this._blendFunctionParameters = new Array(4);
  10605. this._blendEquationParameters = new Array(2);
  10606. this._blendConstants = new Array(4);
  10607. this.reset();
  10608. }
  10609. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10610. get: function () {
  10611. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10617. get: function () {
  10618. return this._alphaBlend;
  10619. },
  10620. set: function (value) {
  10621. if (this._alphaBlend === value) {
  10622. return;
  10623. }
  10624. this._alphaBlend = value;
  10625. this._isAlphaBlendDirty = true;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10631. if (this._blendConstants[0] === r &&
  10632. this._blendConstants[1] === g &&
  10633. this._blendConstants[2] === b &&
  10634. this._blendConstants[3] === a) {
  10635. return;
  10636. }
  10637. this._blendConstants[0] = r;
  10638. this._blendConstants[1] = g;
  10639. this._blendConstants[2] = b;
  10640. this._blendConstants[3] = a;
  10641. this._isBlendConstantsDirty = true;
  10642. };
  10643. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10644. if (this._blendFunctionParameters[0] === value0 &&
  10645. this._blendFunctionParameters[1] === value1 &&
  10646. this._blendFunctionParameters[2] === value2 &&
  10647. this._blendFunctionParameters[3] === value3) {
  10648. return;
  10649. }
  10650. this._blendFunctionParameters[0] = value0;
  10651. this._blendFunctionParameters[1] = value1;
  10652. this._blendFunctionParameters[2] = value2;
  10653. this._blendFunctionParameters[3] = value3;
  10654. this._isBlendFunctionParametersDirty = true;
  10655. };
  10656. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10657. if (this._blendEquationParameters[0] === rgb &&
  10658. this._blendEquationParameters[1] === alpha) {
  10659. return;
  10660. }
  10661. this._blendEquationParameters[0] = rgb;
  10662. this._blendEquationParameters[1] = alpha;
  10663. this._isBlendEquationParametersDirty = true;
  10664. };
  10665. _AlphaState.prototype.reset = function () {
  10666. this._alphaBlend = false;
  10667. this._blendFunctionParameters[0] = null;
  10668. this._blendFunctionParameters[1] = null;
  10669. this._blendFunctionParameters[2] = null;
  10670. this._blendFunctionParameters[3] = null;
  10671. this._blendEquationParameters[0] = null;
  10672. this._blendEquationParameters[1] = null;
  10673. this._blendConstants[0] = null;
  10674. this._blendConstants[1] = null;
  10675. this._blendConstants[2] = null;
  10676. this._blendConstants[3] = null;
  10677. this._isAlphaBlendDirty = true;
  10678. this._isBlendFunctionParametersDirty = false;
  10679. this._isBlendEquationParametersDirty = false;
  10680. this._isBlendConstantsDirty = false;
  10681. };
  10682. _AlphaState.prototype.apply = function (gl) {
  10683. if (!this.isDirty) {
  10684. return;
  10685. }
  10686. // Alpha blend
  10687. if (this._isAlphaBlendDirty) {
  10688. if (this._alphaBlend) {
  10689. gl.enable(gl.BLEND);
  10690. }
  10691. else {
  10692. gl.disable(gl.BLEND);
  10693. }
  10694. this._isAlphaBlendDirty = false;
  10695. }
  10696. // Alpha function
  10697. if (this._isBlendFunctionParametersDirty) {
  10698. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10699. this._isBlendFunctionParametersDirty = false;
  10700. }
  10701. // Alpha equation
  10702. if (this._isBlendEquationParametersDirty) {
  10703. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10704. this._isBlendEquationParametersDirty = false;
  10705. }
  10706. // Constants
  10707. if (this._isBlendConstantsDirty) {
  10708. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10709. this._isBlendConstantsDirty = false;
  10710. }
  10711. };
  10712. return _AlphaState;
  10713. }());
  10714. BABYLON._AlphaState = _AlphaState;
  10715. })(BABYLON || (BABYLON = {}));
  10716. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10717. var BABYLON;
  10718. (function (BABYLON) {
  10719. /**
  10720. * @hidden
  10721. **/
  10722. var _DepthCullingState = /** @class */ (function () {
  10723. /**
  10724. * Initializes the state.
  10725. */
  10726. function _DepthCullingState() {
  10727. this._isDepthTestDirty = false;
  10728. this._isDepthMaskDirty = false;
  10729. this._isDepthFuncDirty = false;
  10730. this._isCullFaceDirty = false;
  10731. this._isCullDirty = false;
  10732. this._isZOffsetDirty = false;
  10733. this._isFrontFaceDirty = false;
  10734. this.reset();
  10735. }
  10736. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10737. get: function () {
  10738. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10744. get: function () {
  10745. return this._zOffset;
  10746. },
  10747. set: function (value) {
  10748. if (this._zOffset === value) {
  10749. return;
  10750. }
  10751. this._zOffset = value;
  10752. this._isZOffsetDirty = true;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10758. get: function () {
  10759. return this._cullFace;
  10760. },
  10761. set: function (value) {
  10762. if (this._cullFace === value) {
  10763. return;
  10764. }
  10765. this._cullFace = value;
  10766. this._isCullFaceDirty = true;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10772. get: function () {
  10773. return this._cull;
  10774. },
  10775. set: function (value) {
  10776. if (this._cull === value) {
  10777. return;
  10778. }
  10779. this._cull = value;
  10780. this._isCullDirty = true;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10786. get: function () {
  10787. return this._depthFunc;
  10788. },
  10789. set: function (value) {
  10790. if (this._depthFunc === value) {
  10791. return;
  10792. }
  10793. this._depthFunc = value;
  10794. this._isDepthFuncDirty = true;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10800. get: function () {
  10801. return this._depthMask;
  10802. },
  10803. set: function (value) {
  10804. if (this._depthMask === value) {
  10805. return;
  10806. }
  10807. this._depthMask = value;
  10808. this._isDepthMaskDirty = true;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10814. get: function () {
  10815. return this._depthTest;
  10816. },
  10817. set: function (value) {
  10818. if (this._depthTest === value) {
  10819. return;
  10820. }
  10821. this._depthTest = value;
  10822. this._isDepthTestDirty = true;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10828. get: function () {
  10829. return this._frontFace;
  10830. },
  10831. set: function (value) {
  10832. if (this._frontFace === value) {
  10833. return;
  10834. }
  10835. this._frontFace = value;
  10836. this._isFrontFaceDirty = true;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. _DepthCullingState.prototype.reset = function () {
  10842. this._depthMask = true;
  10843. this._depthTest = true;
  10844. this._depthFunc = null;
  10845. this._cullFace = null;
  10846. this._cull = null;
  10847. this._zOffset = 0;
  10848. this._frontFace = null;
  10849. this._isDepthTestDirty = true;
  10850. this._isDepthMaskDirty = true;
  10851. this._isDepthFuncDirty = false;
  10852. this._isCullFaceDirty = false;
  10853. this._isCullDirty = false;
  10854. this._isZOffsetDirty = false;
  10855. this._isFrontFaceDirty = false;
  10856. };
  10857. _DepthCullingState.prototype.apply = function (gl) {
  10858. if (!this.isDirty) {
  10859. return;
  10860. }
  10861. // Cull
  10862. if (this._isCullDirty) {
  10863. if (this.cull) {
  10864. gl.enable(gl.CULL_FACE);
  10865. }
  10866. else {
  10867. gl.disable(gl.CULL_FACE);
  10868. }
  10869. this._isCullDirty = false;
  10870. }
  10871. // Cull face
  10872. if (this._isCullFaceDirty) {
  10873. gl.cullFace(this.cullFace);
  10874. this._isCullFaceDirty = false;
  10875. }
  10876. // Depth mask
  10877. if (this._isDepthMaskDirty) {
  10878. gl.depthMask(this.depthMask);
  10879. this._isDepthMaskDirty = false;
  10880. }
  10881. // Depth test
  10882. if (this._isDepthTestDirty) {
  10883. if (this.depthTest) {
  10884. gl.enable(gl.DEPTH_TEST);
  10885. }
  10886. else {
  10887. gl.disable(gl.DEPTH_TEST);
  10888. }
  10889. this._isDepthTestDirty = false;
  10890. }
  10891. // Depth func
  10892. if (this._isDepthFuncDirty) {
  10893. gl.depthFunc(this.depthFunc);
  10894. this._isDepthFuncDirty = false;
  10895. }
  10896. // zOffset
  10897. if (this._isZOffsetDirty) {
  10898. if (this.zOffset) {
  10899. gl.enable(gl.POLYGON_OFFSET_FILL);
  10900. gl.polygonOffset(this.zOffset, 0);
  10901. }
  10902. else {
  10903. gl.disable(gl.POLYGON_OFFSET_FILL);
  10904. }
  10905. this._isZOffsetDirty = false;
  10906. }
  10907. // Front face
  10908. if (this._isFrontFaceDirty) {
  10909. gl.frontFace(this.frontFace);
  10910. this._isFrontFaceDirty = false;
  10911. }
  10912. };
  10913. return _DepthCullingState;
  10914. }());
  10915. BABYLON._DepthCullingState = _DepthCullingState;
  10916. })(BABYLON || (BABYLON = {}));
  10917. //# sourceMappingURL=babylon.depthCullingState.js.map
  10918. var BABYLON;
  10919. (function (BABYLON) {
  10920. /**
  10921. * @hidden
  10922. **/
  10923. var _StencilState = /** @class */ (function () {
  10924. function _StencilState() {
  10925. this._isStencilTestDirty = false;
  10926. this._isStencilMaskDirty = false;
  10927. this._isStencilFuncDirty = false;
  10928. this._isStencilOpDirty = false;
  10929. this.reset();
  10930. }
  10931. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10932. get: function () {
  10933. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10934. },
  10935. enumerable: true,
  10936. configurable: true
  10937. });
  10938. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10939. get: function () {
  10940. return this._stencilFunc;
  10941. },
  10942. set: function (value) {
  10943. if (this._stencilFunc === value) {
  10944. return;
  10945. }
  10946. this._stencilFunc = value;
  10947. this._isStencilFuncDirty = true;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10953. get: function () {
  10954. return this._stencilFuncRef;
  10955. },
  10956. set: function (value) {
  10957. if (this._stencilFuncRef === value) {
  10958. return;
  10959. }
  10960. this._stencilFuncRef = value;
  10961. this._isStencilFuncDirty = true;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10967. get: function () {
  10968. return this._stencilFuncMask;
  10969. },
  10970. set: function (value) {
  10971. if (this._stencilFuncMask === value) {
  10972. return;
  10973. }
  10974. this._stencilFuncMask = value;
  10975. this._isStencilFuncDirty = true;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10981. get: function () {
  10982. return this._stencilOpStencilFail;
  10983. },
  10984. set: function (value) {
  10985. if (this._stencilOpStencilFail === value) {
  10986. return;
  10987. }
  10988. this._stencilOpStencilFail = value;
  10989. this._isStencilOpDirty = true;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10995. get: function () {
  10996. return this._stencilOpDepthFail;
  10997. },
  10998. set: function (value) {
  10999. if (this._stencilOpDepthFail === value) {
  11000. return;
  11001. }
  11002. this._stencilOpDepthFail = value;
  11003. this._isStencilOpDirty = true;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11009. get: function () {
  11010. return this._stencilOpStencilDepthPass;
  11011. },
  11012. set: function (value) {
  11013. if (this._stencilOpStencilDepthPass === value) {
  11014. return;
  11015. }
  11016. this._stencilOpStencilDepthPass = value;
  11017. this._isStencilOpDirty = true;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11023. get: function () {
  11024. return this._stencilMask;
  11025. },
  11026. set: function (value) {
  11027. if (this._stencilMask === value) {
  11028. return;
  11029. }
  11030. this._stencilMask = value;
  11031. this._isStencilMaskDirty = true;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11037. get: function () {
  11038. return this._stencilTest;
  11039. },
  11040. set: function (value) {
  11041. if (this._stencilTest === value) {
  11042. return;
  11043. }
  11044. this._stencilTest = value;
  11045. this._isStencilTestDirty = true;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. _StencilState.prototype.reset = function () {
  11051. this._stencilTest = false;
  11052. this._stencilMask = 0xFF;
  11053. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11054. this._stencilFuncRef = 1;
  11055. this._stencilFuncMask = 0xFF;
  11056. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11057. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11058. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11059. this._isStencilTestDirty = true;
  11060. this._isStencilMaskDirty = true;
  11061. this._isStencilFuncDirty = true;
  11062. this._isStencilOpDirty = true;
  11063. };
  11064. _StencilState.prototype.apply = function (gl) {
  11065. if (!this.isDirty) {
  11066. return;
  11067. }
  11068. // Stencil test
  11069. if (this._isStencilTestDirty) {
  11070. if (this.stencilTest) {
  11071. gl.enable(gl.STENCIL_TEST);
  11072. }
  11073. else {
  11074. gl.disable(gl.STENCIL_TEST);
  11075. }
  11076. this._isStencilTestDirty = false;
  11077. }
  11078. // Stencil mask
  11079. if (this._isStencilMaskDirty) {
  11080. gl.stencilMask(this.stencilMask);
  11081. this._isStencilMaskDirty = false;
  11082. }
  11083. // Stencil func
  11084. if (this._isStencilFuncDirty) {
  11085. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11086. this._isStencilFuncDirty = false;
  11087. }
  11088. // Stencil op
  11089. if (this._isStencilOpDirty) {
  11090. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11091. this._isStencilOpDirty = false;
  11092. }
  11093. };
  11094. return _StencilState;
  11095. }());
  11096. BABYLON._StencilState = _StencilState;
  11097. })(BABYLON || (BABYLON = {}));
  11098. //# sourceMappingURL=babylon.stencilState.js.map
  11099. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11100. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11101. s = arguments[i];
  11102. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11103. t[p] = s[p];
  11104. }
  11105. return t;
  11106. };
  11107. var BABYLON;
  11108. (function (BABYLON) {
  11109. /**
  11110. * Keeps track of all the buffer info used in engine.
  11111. */
  11112. var BufferPointer = /** @class */ (function () {
  11113. function BufferPointer() {
  11114. }
  11115. return BufferPointer;
  11116. }());
  11117. /**
  11118. * Interface for attribute information associated with buffer instanciation
  11119. */
  11120. var InstancingAttributeInfo = /** @class */ (function () {
  11121. function InstancingAttributeInfo() {
  11122. }
  11123. return InstancingAttributeInfo;
  11124. }());
  11125. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11126. /**
  11127. * Define options used to create a render target texture
  11128. */
  11129. var RenderTargetCreationOptions = /** @class */ (function () {
  11130. function RenderTargetCreationOptions() {
  11131. }
  11132. return RenderTargetCreationOptions;
  11133. }());
  11134. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11135. /**
  11136. * Define options used to create a depth texture
  11137. */
  11138. var DepthTextureCreationOptions = /** @class */ (function () {
  11139. function DepthTextureCreationOptions() {
  11140. }
  11141. return DepthTextureCreationOptions;
  11142. }());
  11143. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11144. /**
  11145. * Class used to describe the capabilities of the engine relatively to the current browser
  11146. */
  11147. var EngineCapabilities = /** @class */ (function () {
  11148. function EngineCapabilities() {
  11149. }
  11150. return EngineCapabilities;
  11151. }());
  11152. BABYLON.EngineCapabilities = EngineCapabilities;
  11153. /**
  11154. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11155. */
  11156. var Engine = /** @class */ (function () {
  11157. /**
  11158. * Creates a new engine
  11159. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11160. * @param antialias defines enable antialiasing (default: false)
  11161. * @param options defines further options to be sent to the getContext() function
  11162. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11163. */
  11164. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11165. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11166. var _this = this;
  11167. // Public members
  11168. /**
  11169. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11170. */
  11171. this.forcePOTTextures = false;
  11172. /**
  11173. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11174. */
  11175. this.isFullscreen = false;
  11176. /**
  11177. * Gets a boolean indicating if the pointer is currently locked
  11178. */
  11179. this.isPointerLock = false;
  11180. /**
  11181. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11182. */
  11183. this.cullBackFaces = true;
  11184. /**
  11185. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11186. */
  11187. this.renderEvenInBackground = true;
  11188. /**
  11189. * Gets or sets a boolean indicating that cache can be kept between frames
  11190. */
  11191. this.preventCacheWipeBetweenFrames = false;
  11192. /**
  11193. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11194. **/
  11195. this.enableOfflineSupport = false;
  11196. /**
  11197. * 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)
  11198. **/
  11199. this.disableManifestCheck = false;
  11200. /**
  11201. * Gets the list of created scenes
  11202. */
  11203. this.scenes = new Array();
  11204. /**
  11205. * Gets the list of created postprocesses
  11206. */
  11207. this.postProcesses = new Array();
  11208. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11209. this.validateShaderPrograms = false;
  11210. // Observables
  11211. /**
  11212. * Observable event triggered each time the rendering canvas is resized
  11213. */
  11214. this.onResizeObservable = new BABYLON.Observable();
  11215. /**
  11216. * Observable event triggered each time the canvas loses focus
  11217. */
  11218. this.onCanvasBlurObservable = new BABYLON.Observable();
  11219. /**
  11220. * Observable event triggered each time the canvas gains focus
  11221. */
  11222. this.onCanvasFocusObservable = new BABYLON.Observable();
  11223. /**
  11224. * Observable event triggered each time the canvas receives pointerout event
  11225. */
  11226. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11227. /**
  11228. * Observable event triggered before each texture is initialized
  11229. */
  11230. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11231. //WebVR
  11232. this._vrDisplay = undefined;
  11233. this._vrSupported = false;
  11234. this._vrExclusivePointerMode = false;
  11235. // Uniform buffers list
  11236. /**
  11237. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11238. */
  11239. this.disableUniformBuffers = false;
  11240. /** @hidden */
  11241. this._uniformBuffers = new Array();
  11242. // Observables
  11243. /**
  11244. * Observable raised when the engine begins a new frame
  11245. */
  11246. this.onBeginFrameObservable = new BABYLON.Observable();
  11247. /**
  11248. * Observable raised when the engine ends the current frame
  11249. */
  11250. this.onEndFrameObservable = new BABYLON.Observable();
  11251. /**
  11252. * Observable raised when the engine is about to compile a shader
  11253. */
  11254. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11255. /**
  11256. * Observable raised when the engine has jsut compiled a shader
  11257. */
  11258. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11259. this._windowIsBackground = false;
  11260. this._webGLVersion = 1.0;
  11261. /** @hidden */
  11262. this._badOS = false;
  11263. /** @hidden */
  11264. this._badDesktopOS = false;
  11265. /**
  11266. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11267. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11268. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11269. */
  11270. this.disableTextureBindingOptimization = false;
  11271. /**
  11272. * Observable signaled when VR display mode changes
  11273. */
  11274. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable signaled when VR request present is complete
  11277. */
  11278. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11279. /**
  11280. * Observable signaled when VR request present starts
  11281. */
  11282. this.onVRRequestPresentStart = new BABYLON.Observable();
  11283. this._colorWrite = true;
  11284. /** @hidden */
  11285. this._drawCalls = new BABYLON.PerfCounter();
  11286. /** @hidden */
  11287. this._textureCollisions = new BABYLON.PerfCounter();
  11288. this._renderingQueueLaunched = false;
  11289. this._activeRenderLoops = new Array();
  11290. // Deterministic lockstepMaxSteps
  11291. this._deterministicLockstep = false;
  11292. this._lockstepMaxSteps = 4;
  11293. // Lost context
  11294. /**
  11295. * Observable signaled when a context lost event is raised
  11296. */
  11297. this.onContextLostObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable signaled when a context restored event is raised
  11300. */
  11301. this.onContextRestoredObservable = new BABYLON.Observable();
  11302. this._contextWasLost = false;
  11303. this._doNotHandleContextLost = false;
  11304. // FPS
  11305. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11306. this._fps = 60;
  11307. this._deltaTime = 0;
  11308. /**
  11309. * Turn this value on if you want to pause FPS computation when in background
  11310. */
  11311. this.disablePerformanceMonitorInBackground = false;
  11312. // States
  11313. /** @hidden */
  11314. this._depthCullingState = new BABYLON._DepthCullingState();
  11315. /** @hidden */
  11316. this._stencilState = new BABYLON._StencilState();
  11317. /** @hidden */
  11318. this._alphaState = new BABYLON._AlphaState();
  11319. /** @hidden */
  11320. this._alphaMode = Engine.ALPHA_DISABLE;
  11321. // Cache
  11322. this._internalTexturesCache = new Array();
  11323. /** @hidden */
  11324. this._activeChannel = 0;
  11325. this._currentTextureChannel = -1;
  11326. /** @hidden */
  11327. this._boundTexturesCache = {};
  11328. this._compiledEffects = {};
  11329. this._vertexAttribArraysEnabled = [];
  11330. this._uintIndicesCurrentlySet = false;
  11331. this._currentBoundBuffer = new Array();
  11332. /** @hidden */
  11333. this._currentFramebuffer = null;
  11334. this._currentBufferPointers = new Array();
  11335. this._currentInstanceLocations = new Array();
  11336. this._currentInstanceBuffers = new Array();
  11337. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11338. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11339. this._vaoRecordInProgress = false;
  11340. this._mustWipeVertexAttributes = false;
  11341. this._nextFreeTextureSlots = new Array();
  11342. this._maxSimultaneousTextures = 0;
  11343. this._activeRequests = new Array();
  11344. // Hardware supported Compressed Textures
  11345. this._texturesSupported = new Array();
  11346. /**
  11347. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11348. */
  11349. this.premultipliedAlpha = true;
  11350. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11351. this._onVRFullScreenTriggered = function () {
  11352. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11353. //get the old size before we change
  11354. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11355. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11356. //get the width and height, change the render size
  11357. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11358. _this.setHardwareScalingLevel(1);
  11359. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11360. }
  11361. else {
  11362. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11363. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11364. }
  11365. };
  11366. this._unpackFlipYCached = null;
  11367. this._boundUniforms = {};
  11368. // Register promises
  11369. BABYLON.PromisePolyfill.Apply();
  11370. var canvas = null;
  11371. Engine.Instances.push(this);
  11372. if (!canvasOrContext) {
  11373. return;
  11374. }
  11375. options = options || {};
  11376. if (canvasOrContext.getContext) {
  11377. canvas = canvasOrContext;
  11378. this._renderingCanvas = canvas;
  11379. if (antialias != null) {
  11380. options.antialias = antialias;
  11381. }
  11382. if (options.deterministicLockstep === undefined) {
  11383. options.deterministicLockstep = false;
  11384. }
  11385. if (options.lockstepMaxSteps === undefined) {
  11386. options.lockstepMaxSteps = 4;
  11387. }
  11388. if (options.preserveDrawingBuffer === undefined) {
  11389. options.preserveDrawingBuffer = false;
  11390. }
  11391. if (options.audioEngine === undefined) {
  11392. options.audioEngine = true;
  11393. }
  11394. if (options.stencil === undefined) {
  11395. options.stencil = true;
  11396. }
  11397. if (options.premultipliedAlpha === false) {
  11398. this.premultipliedAlpha = false;
  11399. }
  11400. this._deterministicLockstep = options.deterministicLockstep;
  11401. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11402. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11403. // Exceptions
  11404. if (navigator && navigator.userAgent) {
  11405. var ua = navigator.userAgent;
  11406. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11407. var exception = _a[_i];
  11408. var key = exception.key;
  11409. var targets = exception.targets;
  11410. if (ua.indexOf(key) > -1) {
  11411. if (exception.capture && exception.captureConstraint) {
  11412. var capture = exception.capture;
  11413. var constraint = exception.captureConstraint;
  11414. var regex = new RegExp(capture);
  11415. var matches = regex.exec(ua);
  11416. if (matches && matches.length > 0) {
  11417. var capturedValue = parseInt(matches[matches.length - 1]);
  11418. if (capturedValue >= constraint) {
  11419. continue;
  11420. }
  11421. }
  11422. }
  11423. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11424. var target = targets_1[_b];
  11425. switch (target) {
  11426. case "uniformBuffer":
  11427. this.disableUniformBuffers = true;
  11428. break;
  11429. case "textureBindingOptimization":
  11430. this.disableTextureBindingOptimization = true;
  11431. break;
  11432. }
  11433. }
  11434. }
  11435. }
  11436. }
  11437. // GL
  11438. if (!options.disableWebGL2Support) {
  11439. try {
  11440. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11441. if (this._gl) {
  11442. this._webGLVersion = 2.0;
  11443. }
  11444. }
  11445. catch (e) {
  11446. // Do nothing
  11447. }
  11448. }
  11449. if (!this._gl) {
  11450. if (!canvas) {
  11451. throw new Error("The provided canvas is null or undefined.");
  11452. }
  11453. try {
  11454. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11455. }
  11456. catch (e) {
  11457. throw new Error("WebGL not supported");
  11458. }
  11459. }
  11460. if (!this._gl) {
  11461. throw new Error("WebGL not supported");
  11462. }
  11463. this._onCanvasFocus = function () {
  11464. _this.onCanvasFocusObservable.notifyObservers(_this);
  11465. };
  11466. this._onCanvasBlur = function () {
  11467. _this.onCanvasBlurObservable.notifyObservers(_this);
  11468. };
  11469. canvas.addEventListener("focus", this._onCanvasFocus);
  11470. canvas.addEventListener("blur", this._onCanvasBlur);
  11471. this._onBlur = function () {
  11472. if (_this.disablePerformanceMonitorInBackground) {
  11473. _this._performanceMonitor.disable();
  11474. }
  11475. _this._windowIsBackground = true;
  11476. };
  11477. this._onFocus = function () {
  11478. if (_this.disablePerformanceMonitorInBackground) {
  11479. _this._performanceMonitor.enable();
  11480. }
  11481. _this._windowIsBackground = false;
  11482. };
  11483. this._onCanvasPointerOut = function (ev) {
  11484. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11485. };
  11486. window.addEventListener("blur", this._onBlur);
  11487. window.addEventListener("focus", this._onFocus);
  11488. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11489. // Context lost
  11490. if (!this._doNotHandleContextLost) {
  11491. this._onContextLost = function (evt) {
  11492. evt.preventDefault();
  11493. _this._contextWasLost = true;
  11494. BABYLON.Tools.Warn("WebGL context lost.");
  11495. _this.onContextLostObservable.notifyObservers(_this);
  11496. };
  11497. this._onContextRestored = function (evt) {
  11498. // Adding a timeout to avoid race condition at browser level
  11499. setTimeout(function () {
  11500. // Rebuild gl context
  11501. _this._initGLContext();
  11502. // Rebuild effects
  11503. _this._rebuildEffects();
  11504. // Rebuild textures
  11505. _this._rebuildInternalTextures();
  11506. // Rebuild buffers
  11507. _this._rebuildBuffers();
  11508. // Cache
  11509. _this.wipeCaches(true);
  11510. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11511. _this.onContextRestoredObservable.notifyObservers(_this);
  11512. _this._contextWasLost = false;
  11513. }, 0);
  11514. };
  11515. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11516. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11517. }
  11518. }
  11519. else {
  11520. this._gl = canvasOrContext;
  11521. this._renderingCanvas = this._gl.canvas;
  11522. if (this._gl.renderbufferStorageMultisample) {
  11523. this._webGLVersion = 2.0;
  11524. }
  11525. options.stencil = this._gl.getContextAttributes().stencil;
  11526. }
  11527. // Viewport
  11528. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11529. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11530. this.resize();
  11531. this._isStencilEnable = options.stencil ? true : false;
  11532. this._initGLContext();
  11533. if (canvas) {
  11534. // Fullscreen
  11535. this._onFullscreenChange = function () {
  11536. if (document.fullscreen !== undefined) {
  11537. _this.isFullscreen = document.fullscreen;
  11538. }
  11539. else if (document.mozFullScreen !== undefined) {
  11540. _this.isFullscreen = document.mozFullScreen;
  11541. }
  11542. else if (document.webkitIsFullScreen !== undefined) {
  11543. _this.isFullscreen = document.webkitIsFullScreen;
  11544. }
  11545. else if (document.msIsFullScreen !== undefined) {
  11546. _this.isFullscreen = document.msIsFullScreen;
  11547. }
  11548. // Pointer lock
  11549. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11550. canvas.requestPointerLock = canvas.requestPointerLock ||
  11551. canvas.msRequestPointerLock ||
  11552. canvas.mozRequestPointerLock ||
  11553. canvas.webkitRequestPointerLock;
  11554. if (canvas.requestPointerLock) {
  11555. canvas.requestPointerLock();
  11556. }
  11557. }
  11558. };
  11559. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11560. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11561. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11562. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11563. // Pointer lock
  11564. this._onPointerLockChange = function () {
  11565. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11566. document.webkitPointerLockElement === canvas ||
  11567. document.msPointerLockElement === canvas ||
  11568. document.pointerLockElement === canvas);
  11569. };
  11570. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11571. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11572. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11573. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11574. this._onVRDisplayPointerRestricted = function () {
  11575. if (canvas) {
  11576. canvas.requestPointerLock();
  11577. }
  11578. };
  11579. this._onVRDisplayPointerUnrestricted = function () {
  11580. document.exitPointerLock();
  11581. };
  11582. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11583. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11584. }
  11585. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11586. Engine.audioEngine = new BABYLON.AudioEngine();
  11587. }
  11588. // Prepare buffer pointers
  11589. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11590. this._currentBufferPointers[i] = new BufferPointer();
  11591. }
  11592. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11593. // Load WebVR Devices
  11594. if (options.autoEnableWebVR) {
  11595. this.initWebVR();
  11596. }
  11597. // Detect if we are running on a faulty buggy OS.
  11598. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11599. // Detect if we are running on a faulty buggy desktop OS.
  11600. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11601. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11602. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11603. }
  11604. Object.defineProperty(Engine, "LastCreatedEngine", {
  11605. /**
  11606. * Gets the latest created engine
  11607. */
  11608. get: function () {
  11609. if (Engine.Instances.length === 0) {
  11610. return null;
  11611. }
  11612. return Engine.Instances[Engine.Instances.length - 1];
  11613. },
  11614. enumerable: true,
  11615. configurable: true
  11616. });
  11617. Object.defineProperty(Engine, "LastCreatedScene", {
  11618. /**
  11619. * Gets the latest created scene
  11620. */
  11621. get: function () {
  11622. var lastCreatedEngine = Engine.LastCreatedEngine;
  11623. if (!lastCreatedEngine) {
  11624. return null;
  11625. }
  11626. if (lastCreatedEngine.scenes.length === 0) {
  11627. return null;
  11628. }
  11629. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. /**
  11635. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11636. * @param flag defines which part of the materials must be marked as dirty
  11637. * @param predicate defines a predicate used to filter which materials should be affected
  11638. */
  11639. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11640. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11641. var engine = Engine.Instances[engineIndex];
  11642. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11643. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11644. }
  11645. }
  11646. };
  11647. Object.defineProperty(Engine, "Version", {
  11648. /**
  11649. * Returns the current version of the framework
  11650. */
  11651. get: function () {
  11652. return "3.3.0-alpha.12";
  11653. },
  11654. enumerable: true,
  11655. configurable: true
  11656. });
  11657. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11658. /**
  11659. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11660. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11661. */
  11662. get: function () {
  11663. return this._vrExclusivePointerMode;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11669. /**
  11670. * Gets a boolean indicating that the engine supports uniform buffers
  11671. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11672. */
  11673. get: function () {
  11674. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11680. /**
  11681. * Gets a boolean indicating that only power of 2 textures are supported
  11682. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11683. */
  11684. get: function () {
  11685. return this._webGLVersion < 2 || this.forcePOTTextures;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11691. /**
  11692. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11693. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11694. */
  11695. get: function () {
  11696. return this._doNotHandleContextLost;
  11697. },
  11698. set: function (value) {
  11699. this._doNotHandleContextLost = value;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11705. /**
  11706. * Gets the performance monitor attached to this engine
  11707. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11708. */
  11709. get: function () {
  11710. return this._performanceMonitor;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11716. /**
  11717. * Gets the list of texture formats supported
  11718. */
  11719. get: function () {
  11720. return this._texturesSupported;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11726. /**
  11727. * Gets the list of texture formats in use
  11728. */
  11729. get: function () {
  11730. return this._textureFormatInUse;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine.prototype, "currentViewport", {
  11736. /**
  11737. * Gets the current viewport
  11738. */
  11739. get: function () {
  11740. return this._cachedViewport;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11746. /**
  11747. * Gets the default empty texture
  11748. */
  11749. get: function () {
  11750. if (!this._emptyTexture) {
  11751. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11752. }
  11753. return this._emptyTexture;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11759. /**
  11760. * Gets the default empty 3D texture
  11761. */
  11762. get: function () {
  11763. if (!this._emptyTexture3D) {
  11764. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11765. }
  11766. return this._emptyTexture3D;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11772. /**
  11773. * Gets the default empty cube texture
  11774. */
  11775. get: function () {
  11776. if (!this._emptyCubeTexture) {
  11777. var faceData = new Uint8Array(4);
  11778. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11779. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11780. }
  11781. return this._emptyCubeTexture;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Engine.prototype._rebuildInternalTextures = function () {
  11787. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11788. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11789. var internalTexture = currentState_1[_i];
  11790. internalTexture._rebuild();
  11791. }
  11792. };
  11793. Engine.prototype._rebuildEffects = function () {
  11794. for (var key in this._compiledEffects) {
  11795. var effect = this._compiledEffects[key];
  11796. effect._prepareEffect();
  11797. }
  11798. BABYLON.Effect.ResetCache();
  11799. };
  11800. Engine.prototype._rebuildBuffers = function () {
  11801. // Index / Vertex
  11802. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11803. var scene = _a[_i];
  11804. scene.resetCachedMaterial();
  11805. scene._rebuildGeometries();
  11806. scene._rebuildTextures();
  11807. }
  11808. // Uniforms
  11809. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11810. var uniformBuffer = _c[_b];
  11811. uniformBuffer._rebuild();
  11812. }
  11813. };
  11814. Engine.prototype._initGLContext = function () {
  11815. // Caps
  11816. this._caps = new EngineCapabilities();
  11817. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11818. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11819. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11820. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11821. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11822. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11823. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11824. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11825. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11826. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11827. // Infos
  11828. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11829. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11830. if (rendererInfo != null) {
  11831. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11832. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11833. }
  11834. if (!this._glVendor) {
  11835. this._glVendor = "Unknown vendor";
  11836. }
  11837. if (!this._glRenderer) {
  11838. this._glRenderer = "Unknown renderer";
  11839. }
  11840. // Constants
  11841. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11842. if (this._gl.RGBA16F !== 0x881A) {
  11843. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11844. }
  11845. if (this._gl.RGBA32F !== 0x8814) {
  11846. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11847. }
  11848. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11849. this._gl.DEPTH24_STENCIL8 = 35056;
  11850. }
  11851. // Extensions
  11852. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11853. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11854. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11855. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11856. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11857. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11858. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11859. 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');
  11860. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11861. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11862. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11863. this._caps.highPrecisionShaderSupported = true;
  11864. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11865. if (this._caps.timerQuery) {
  11866. if (this._webGLVersion === 1) {
  11867. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11868. }
  11869. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11870. }
  11871. // Checks if some of the format renders first to allow the use of webgl inspector.
  11872. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11873. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11874. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11875. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11876. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11877. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11878. if (this._webGLVersion > 1) {
  11879. this._gl.HALF_FLOAT_OES = 0x140B;
  11880. }
  11881. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11882. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11883. // Draw buffers
  11884. if (this._webGLVersion > 1) {
  11885. this._caps.drawBuffersExtension = true;
  11886. }
  11887. else {
  11888. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11889. if (drawBuffersExtension !== null) {
  11890. this._caps.drawBuffersExtension = true;
  11891. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11892. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11893. for (var i = 0; i < 16; i++) {
  11894. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11895. }
  11896. }
  11897. else {
  11898. this._caps.drawBuffersExtension = false;
  11899. }
  11900. }
  11901. // Depth Texture
  11902. if (this._webGLVersion > 1) {
  11903. this._caps.depthTextureExtension = true;
  11904. }
  11905. else {
  11906. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11907. if (depthTextureExtension != null) {
  11908. this._caps.depthTextureExtension = true;
  11909. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11910. }
  11911. }
  11912. // Vertex array object
  11913. if (this._webGLVersion > 1) {
  11914. this._caps.vertexArrayObject = true;
  11915. }
  11916. else {
  11917. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11918. if (vertexArrayObjectExtension != null) {
  11919. this._caps.vertexArrayObject = true;
  11920. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11921. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11922. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11923. }
  11924. else {
  11925. this._caps.vertexArrayObject = false;
  11926. }
  11927. }
  11928. // Instances count
  11929. if (this._webGLVersion > 1) {
  11930. this._caps.instancedArrays = true;
  11931. }
  11932. else {
  11933. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11934. if (instanceExtension != null) {
  11935. this._caps.instancedArrays = true;
  11936. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11937. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11938. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11939. }
  11940. else {
  11941. this._caps.instancedArrays = false;
  11942. }
  11943. }
  11944. // Intelligently add supported compressed formats in order to check for.
  11945. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11946. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11947. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11948. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11949. if (this._caps.astc)
  11950. this.texturesSupported.push('-astc.ktx');
  11951. if (this._caps.s3tc)
  11952. this.texturesSupported.push('-dxt.ktx');
  11953. if (this._caps.pvrtc)
  11954. this.texturesSupported.push('-pvrtc.ktx');
  11955. if (this._caps.etc2)
  11956. this.texturesSupported.push('-etc2.ktx');
  11957. if (this._caps.etc1)
  11958. this.texturesSupported.push('-etc1.ktx');
  11959. if (this._gl.getShaderPrecisionFormat) {
  11960. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11961. if (highp) {
  11962. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11963. }
  11964. }
  11965. // Depth buffer
  11966. this.setDepthBuffer(true);
  11967. this.setDepthFunctionToLessOrEqual();
  11968. this.setDepthWrite(true);
  11969. // Texture maps
  11970. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11971. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11972. this._nextFreeTextureSlots.push(slot);
  11973. }
  11974. };
  11975. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11976. /**
  11977. * Gets version of the current webGL context
  11978. */
  11979. get: function () {
  11980. return this._webGLVersion;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11986. /**
  11987. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11988. */
  11989. get: function () {
  11990. return this._isStencilEnable;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Engine.prototype._prepareWorkingCanvas = function () {
  11996. if (this._workingCanvas) {
  11997. return;
  11998. }
  11999. this._workingCanvas = document.createElement("canvas");
  12000. var context = this._workingCanvas.getContext("2d");
  12001. if (context) {
  12002. this._workingContext = context;
  12003. }
  12004. };
  12005. /**
  12006. * Reset the texture cache to empty state
  12007. */
  12008. Engine.prototype.resetTextureCache = function () {
  12009. for (var key in this._boundTexturesCache) {
  12010. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12011. continue;
  12012. }
  12013. var boundTexture = this._boundTexturesCache[key];
  12014. if (boundTexture) {
  12015. this._removeDesignatedSlot(boundTexture);
  12016. }
  12017. this._boundTexturesCache[key] = null;
  12018. }
  12019. if (!this.disableTextureBindingOptimization) {
  12020. this._nextFreeTextureSlots = [];
  12021. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12022. this._nextFreeTextureSlots.push(slot);
  12023. }
  12024. }
  12025. this._currentTextureChannel = -1;
  12026. };
  12027. /**
  12028. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12029. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12030. * @returns true if engine is in deterministic lock step mode
  12031. */
  12032. Engine.prototype.isDeterministicLockStep = function () {
  12033. return this._deterministicLockstep;
  12034. };
  12035. /**
  12036. * Gets the max steps when engine is running in deterministic lock step
  12037. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12038. * @returns the max steps
  12039. */
  12040. Engine.prototype.getLockstepMaxSteps = function () {
  12041. return this._lockstepMaxSteps;
  12042. };
  12043. /**
  12044. * Gets an object containing information about the current webGL context
  12045. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12046. */
  12047. Engine.prototype.getGlInfo = function () {
  12048. return {
  12049. vendor: this._glVendor,
  12050. renderer: this._glRenderer,
  12051. version: this._glVersion
  12052. };
  12053. };
  12054. /**
  12055. * Gets current aspect ratio
  12056. * @param camera defines the camera to use to get the aspect ratio
  12057. * @param useScreen defines if screen size must be used (or the current render target if any)
  12058. * @returns a number defining the aspect ratio
  12059. */
  12060. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12061. if (useScreen === void 0) { useScreen = false; }
  12062. var viewport = camera.viewport;
  12063. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12064. };
  12065. /**
  12066. * Gets current screen aspect ratio
  12067. * @returns a number defining the aspect ratio
  12068. */
  12069. Engine.prototype.getScreenAspectRatio = function () {
  12070. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12071. };
  12072. /**
  12073. * Gets the current render width
  12074. * @param useScreen defines if screen size must be used (or the current render target if any)
  12075. * @returns a number defining the current render width
  12076. */
  12077. Engine.prototype.getRenderWidth = function (useScreen) {
  12078. if (useScreen === void 0) { useScreen = false; }
  12079. if (!useScreen && this._currentRenderTarget) {
  12080. return this._currentRenderTarget.width;
  12081. }
  12082. return this._gl.drawingBufferWidth;
  12083. };
  12084. /**
  12085. * Gets the current render height
  12086. * @param useScreen defines if screen size must be used (or the current render target if any)
  12087. * @returns a number defining the current render height
  12088. */
  12089. Engine.prototype.getRenderHeight = function (useScreen) {
  12090. if (useScreen === void 0) { useScreen = false; }
  12091. if (!useScreen && this._currentRenderTarget) {
  12092. return this._currentRenderTarget.height;
  12093. }
  12094. return this._gl.drawingBufferHeight;
  12095. };
  12096. /**
  12097. * Gets the HTML canvas attached with the current webGL context
  12098. * @returns a HTML canvas
  12099. */
  12100. Engine.prototype.getRenderingCanvas = function () {
  12101. return this._renderingCanvas;
  12102. };
  12103. /**
  12104. * Gets the client rect of the HTML canvas attached with the current webGL context
  12105. * @returns a client rectanglee
  12106. */
  12107. Engine.prototype.getRenderingCanvasClientRect = function () {
  12108. if (!this._renderingCanvas) {
  12109. return null;
  12110. }
  12111. return this._renderingCanvas.getBoundingClientRect();
  12112. };
  12113. /**
  12114. * Defines the hardware scaling level.
  12115. * By default the hardware scaling level is computed from the window device ratio.
  12116. * 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.
  12117. * @param level defines the level to use
  12118. */
  12119. Engine.prototype.setHardwareScalingLevel = function (level) {
  12120. this._hardwareScalingLevel = level;
  12121. this.resize();
  12122. };
  12123. /**
  12124. * Gets the current hardware scaling level.
  12125. * By default the hardware scaling level is computed from the window device ratio.
  12126. * 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.
  12127. * @returns a number indicating the current hardware scaling level
  12128. */
  12129. Engine.prototype.getHardwareScalingLevel = function () {
  12130. return this._hardwareScalingLevel;
  12131. };
  12132. /**
  12133. * Gets the list of loaded textures
  12134. * @returns an array containing all loaded textures
  12135. */
  12136. Engine.prototype.getLoadedTexturesCache = function () {
  12137. return this._internalTexturesCache;
  12138. };
  12139. /**
  12140. * Gets the object containing all engine capabilities
  12141. * @returns the EngineCapabilities object
  12142. */
  12143. Engine.prototype.getCaps = function () {
  12144. return this._caps;
  12145. };
  12146. Object.defineProperty(Engine.prototype, "drawCalls", {
  12147. /** @hidden */
  12148. get: function () {
  12149. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12150. return 0;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12156. /** @hidden */
  12157. get: function () {
  12158. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12159. return null;
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. /**
  12165. * Gets the current depth function
  12166. * @returns a number defining the depth function
  12167. */
  12168. Engine.prototype.getDepthFunction = function () {
  12169. return this._depthCullingState.depthFunc;
  12170. };
  12171. /**
  12172. * Sets the current depth function
  12173. * @param depthFunc defines the function to use
  12174. */
  12175. Engine.prototype.setDepthFunction = function (depthFunc) {
  12176. this._depthCullingState.depthFunc = depthFunc;
  12177. };
  12178. /**
  12179. * Sets the current depth function to GREATER
  12180. */
  12181. Engine.prototype.setDepthFunctionToGreater = function () {
  12182. this._depthCullingState.depthFunc = this._gl.GREATER;
  12183. };
  12184. /**
  12185. * Sets the current depth function to GEQUAL
  12186. */
  12187. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12188. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12189. };
  12190. /**
  12191. * Sets the current depth function to LESS
  12192. */
  12193. Engine.prototype.setDepthFunctionToLess = function () {
  12194. this._depthCullingState.depthFunc = this._gl.LESS;
  12195. };
  12196. /**
  12197. * Sets the current depth function to LEQUAL
  12198. */
  12199. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12200. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12201. };
  12202. /**
  12203. * Gets a boolean indicating if stencil buffer is enabled
  12204. * @returns the current stencil buffer state
  12205. */
  12206. Engine.prototype.getStencilBuffer = function () {
  12207. return this._stencilState.stencilTest;
  12208. };
  12209. /**
  12210. * Enable or disable the stencil buffer
  12211. * @param enable defines if the stencil buffer must be enabled or disabled
  12212. */
  12213. Engine.prototype.setStencilBuffer = function (enable) {
  12214. this._stencilState.stencilTest = enable;
  12215. };
  12216. /**
  12217. * Gets the current stencil mask
  12218. * @returns a number defining the new stencil mask to use
  12219. */
  12220. Engine.prototype.getStencilMask = function () {
  12221. return this._stencilState.stencilMask;
  12222. };
  12223. /**
  12224. * Sets the current stencil mask
  12225. * @param mask defines the new stencil mask to use
  12226. */
  12227. Engine.prototype.setStencilMask = function (mask) {
  12228. this._stencilState.stencilMask = mask;
  12229. };
  12230. /**
  12231. * Gets the current stencil function
  12232. * @returns a number defining the stencil function to use
  12233. */
  12234. Engine.prototype.getStencilFunction = function () {
  12235. return this._stencilState.stencilFunc;
  12236. };
  12237. /**
  12238. * Gets the current stencil reference value
  12239. * @returns a number defining the stencil reference value to use
  12240. */
  12241. Engine.prototype.getStencilFunctionReference = function () {
  12242. return this._stencilState.stencilFuncRef;
  12243. };
  12244. /**
  12245. * Gets the current stencil mask
  12246. * @returns a number defining the stencil mask to use
  12247. */
  12248. Engine.prototype.getStencilFunctionMask = function () {
  12249. return this._stencilState.stencilFuncMask;
  12250. };
  12251. /**
  12252. * Sets the current stencil function
  12253. * @param stencilFunc defines the new stencil function to use
  12254. */
  12255. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12256. this._stencilState.stencilFunc = stencilFunc;
  12257. };
  12258. /**
  12259. * Sets the current stencil reference
  12260. * @param reference defines the new stencil reference to use
  12261. */
  12262. Engine.prototype.setStencilFunctionReference = function (reference) {
  12263. this._stencilState.stencilFuncRef = reference;
  12264. };
  12265. /**
  12266. * Sets the current stencil mask
  12267. * @param mask defines the new stencil mask to use
  12268. */
  12269. Engine.prototype.setStencilFunctionMask = function (mask) {
  12270. this._stencilState.stencilFuncMask = mask;
  12271. };
  12272. /**
  12273. * Gets the current stencil operation when stencil fails
  12274. * @returns a number defining stencil operation to use when stencil fails
  12275. */
  12276. Engine.prototype.getStencilOperationFail = function () {
  12277. return this._stencilState.stencilOpStencilFail;
  12278. };
  12279. /**
  12280. * Gets the current stencil operation when depth fails
  12281. * @returns a number defining stencil operation to use when depth fails
  12282. */
  12283. Engine.prototype.getStencilOperationDepthFail = function () {
  12284. return this._stencilState.stencilOpDepthFail;
  12285. };
  12286. /**
  12287. * Gets the current stencil operation when stencil passes
  12288. * @returns a number defining stencil operation to use when stencil passes
  12289. */
  12290. Engine.prototype.getStencilOperationPass = function () {
  12291. return this._stencilState.stencilOpStencilDepthPass;
  12292. };
  12293. /**
  12294. * Sets the stencil operation to use when stencil fails
  12295. * @param operation defines the stencil operation to use when stencil fails
  12296. */
  12297. Engine.prototype.setStencilOperationFail = function (operation) {
  12298. this._stencilState.stencilOpStencilFail = operation;
  12299. };
  12300. /**
  12301. * Sets the stencil operation to use when depth fails
  12302. * @param operation defines the stencil operation to use when depth fails
  12303. */
  12304. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12305. this._stencilState.stencilOpDepthFail = operation;
  12306. };
  12307. /**
  12308. * Sets the stencil operation to use when stencil passes
  12309. * @param operation defines the stencil operation to use when stencil passes
  12310. */
  12311. Engine.prototype.setStencilOperationPass = function (operation) {
  12312. this._stencilState.stencilOpStencilDepthPass = operation;
  12313. };
  12314. /**
  12315. * Sets a boolean indicating if the dithering state is enabled or disabled
  12316. * @param value defines the dithering state
  12317. */
  12318. Engine.prototype.setDitheringState = function (value) {
  12319. if (value) {
  12320. this._gl.enable(this._gl.DITHER);
  12321. }
  12322. else {
  12323. this._gl.disable(this._gl.DITHER);
  12324. }
  12325. };
  12326. /**
  12327. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12328. * @param value defines the rasterizer state
  12329. */
  12330. Engine.prototype.setRasterizerState = function (value) {
  12331. if (value) {
  12332. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12333. }
  12334. else {
  12335. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12336. }
  12337. };
  12338. /**
  12339. * stop executing a render loop function and remove it from the execution array
  12340. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12341. */
  12342. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12343. if (!renderFunction) {
  12344. this._activeRenderLoops = [];
  12345. return;
  12346. }
  12347. var index = this._activeRenderLoops.indexOf(renderFunction);
  12348. if (index >= 0) {
  12349. this._activeRenderLoops.splice(index, 1);
  12350. }
  12351. };
  12352. /** @hidden */
  12353. Engine.prototype._renderLoop = function () {
  12354. if (!this._contextWasLost) {
  12355. var shouldRender = true;
  12356. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12357. shouldRender = false;
  12358. }
  12359. if (shouldRender) {
  12360. // Start new frame
  12361. this.beginFrame();
  12362. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12363. var renderFunction = this._activeRenderLoops[index];
  12364. renderFunction();
  12365. }
  12366. // Present
  12367. this.endFrame();
  12368. }
  12369. }
  12370. if (this._activeRenderLoops.length > 0) {
  12371. // Register new frame
  12372. var requester = null;
  12373. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12374. requester = this._vrDisplay;
  12375. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12376. }
  12377. else {
  12378. this._renderingQueueLaunched = false;
  12379. }
  12380. };
  12381. /**
  12382. * Register and execute a render loop. The engine can have more than one render function
  12383. * @param renderFunction defines the function to continuously execute
  12384. */
  12385. Engine.prototype.runRenderLoop = function (renderFunction) {
  12386. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12387. return;
  12388. }
  12389. this._activeRenderLoops.push(renderFunction);
  12390. if (!this._renderingQueueLaunched) {
  12391. this._renderingQueueLaunched = true;
  12392. this._bindedRenderFunction = this._renderLoop.bind(this);
  12393. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12394. }
  12395. };
  12396. /**
  12397. * Toggle full screen mode
  12398. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12399. * @param options defines an option object to be sent to the requestFullscreen function
  12400. */
  12401. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12402. if (this.isFullscreen) {
  12403. BABYLON.Tools.ExitFullscreen();
  12404. }
  12405. else {
  12406. this._pointerLockRequested = requestPointerLock;
  12407. if (this._renderingCanvas) {
  12408. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12409. }
  12410. }
  12411. };
  12412. /**
  12413. * Clear the current render buffer or the current render target (if any is set up)
  12414. * @param color defines the color to use
  12415. * @param backBuffer defines if the back buffer must be cleared
  12416. * @param depth defines if the depth buffer must be cleared
  12417. * @param stencil defines if the stencil buffer must be cleared
  12418. */
  12419. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12420. if (stencil === void 0) { stencil = false; }
  12421. this.applyStates();
  12422. var mode = 0;
  12423. if (backBuffer && color) {
  12424. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12425. mode |= this._gl.COLOR_BUFFER_BIT;
  12426. }
  12427. if (depth) {
  12428. this._gl.clearDepth(1.0);
  12429. mode |= this._gl.DEPTH_BUFFER_BIT;
  12430. }
  12431. if (stencil) {
  12432. this._gl.clearStencil(0);
  12433. mode |= this._gl.STENCIL_BUFFER_BIT;
  12434. }
  12435. this._gl.clear(mode);
  12436. };
  12437. /**
  12438. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12439. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12440. * @param y defines the y-coordinate of the corner of the clear rectangle
  12441. * @param width defines the width of the clear rectangle
  12442. * @param height defines the height of the clear rectangle
  12443. * @param clearColor defines the clear color
  12444. */
  12445. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12446. var gl = this._gl;
  12447. // Save state
  12448. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12449. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12450. // Change state
  12451. gl.enable(gl.SCISSOR_TEST);
  12452. gl.scissor(x, y, width, height);
  12453. // Clear
  12454. this.clear(clearColor, true, true, true);
  12455. // Restore state
  12456. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12457. if (curScissor === true) {
  12458. gl.enable(gl.SCISSOR_TEST);
  12459. }
  12460. else {
  12461. gl.disable(gl.SCISSOR_TEST);
  12462. }
  12463. };
  12464. /** @hidden */
  12465. Engine.prototype._viewport = function (x, y, width, height) {
  12466. if (x !== this._viewportCached.x ||
  12467. y !== this._viewportCached.y ||
  12468. width !== this._viewportCached.z ||
  12469. height !== this._viewportCached.w) {
  12470. this._viewportCached.x = x;
  12471. this._viewportCached.y = y;
  12472. this._viewportCached.z = width;
  12473. this._viewportCached.w = height;
  12474. this._gl.viewport(x, y, width, height);
  12475. }
  12476. };
  12477. /**
  12478. * Set the WebGL's viewport
  12479. * @param viewport defines the viewport element to be used
  12480. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12481. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12482. */
  12483. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12484. var width = requiredWidth || this.getRenderWidth();
  12485. var height = requiredHeight || this.getRenderHeight();
  12486. var x = viewport.x || 0;
  12487. var y = viewport.y || 0;
  12488. this._cachedViewport = viewport;
  12489. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12490. };
  12491. /**
  12492. * Directly set the WebGL Viewport
  12493. * @param x defines the x coordinate of the viewport (in screen space)
  12494. * @param y defines the y coordinate of the viewport (in screen space)
  12495. * @param width defines the width of the viewport (in screen space)
  12496. * @param height defines the height of the viewport (in screen space)
  12497. * @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
  12498. */
  12499. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12500. var currentViewport = this._cachedViewport;
  12501. this._cachedViewport = null;
  12502. this._viewport(x, y, width, height);
  12503. return currentViewport;
  12504. };
  12505. /**
  12506. * Begin a new frame
  12507. */
  12508. Engine.prototype.beginFrame = function () {
  12509. this.onBeginFrameObservable.notifyObservers(this);
  12510. this._measureFps();
  12511. };
  12512. /**
  12513. * Enf the current frame
  12514. */
  12515. Engine.prototype.endFrame = function () {
  12516. // Force a flush in case we are using a bad OS.
  12517. if (this._badOS) {
  12518. this.flushFramebuffer();
  12519. }
  12520. // Submit frame to the vr device, if enabled
  12521. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12522. // TODO: We should only submit the frame if we read frameData successfully.
  12523. this._vrDisplay.submitFrame();
  12524. }
  12525. this.onEndFrameObservable.notifyObservers(this);
  12526. };
  12527. /**
  12528. * Resize the view according to the canvas' size
  12529. */
  12530. Engine.prototype.resize = function () {
  12531. // We're not resizing the size of the canvas while in VR mode & presenting
  12532. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12533. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12534. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12535. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12536. }
  12537. };
  12538. /**
  12539. * Force a specific size of the canvas
  12540. * @param width defines the new canvas' width
  12541. * @param height defines the new canvas' height
  12542. */
  12543. Engine.prototype.setSize = function (width, height) {
  12544. if (!this._renderingCanvas) {
  12545. return;
  12546. }
  12547. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12548. return;
  12549. }
  12550. this._renderingCanvas.width = width;
  12551. this._renderingCanvas.height = height;
  12552. for (var index = 0; index < this.scenes.length; index++) {
  12553. var scene = this.scenes[index];
  12554. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12555. var cam = scene.cameras[camIndex];
  12556. cam._currentRenderId = 0;
  12557. }
  12558. }
  12559. if (this.onResizeObservable.hasObservers) {
  12560. this.onResizeObservable.notifyObservers(this);
  12561. }
  12562. };
  12563. // WebVR functions
  12564. /**
  12565. * Gets a boolean indicating if a webVR device was detected
  12566. * @returns true if a webVR device was detected
  12567. */
  12568. Engine.prototype.isVRDevicePresent = function () {
  12569. return !!this._vrDisplay;
  12570. };
  12571. /**
  12572. * Gets the current webVR device
  12573. * @returns the current webVR device (or null)
  12574. */
  12575. Engine.prototype.getVRDevice = function () {
  12576. return this._vrDisplay;
  12577. };
  12578. /**
  12579. * Initializes a webVR display and starts listening to display change events
  12580. * The onVRDisplayChangedObservable will be notified upon these changes
  12581. * @returns The onVRDisplayChangedObservable
  12582. */
  12583. Engine.prototype.initWebVR = function () {
  12584. this.initWebVRAsync();
  12585. return this.onVRDisplayChangedObservable;
  12586. };
  12587. /**
  12588. * Initializes a webVR display and starts listening to display change events
  12589. * The onVRDisplayChangedObservable will be notified upon these changes
  12590. * @returns A promise containing a VRDisplay and if vr is supported
  12591. */
  12592. Engine.prototype.initWebVRAsync = function () {
  12593. var _this = this;
  12594. var notifyObservers = function () {
  12595. var eventArgs = {
  12596. vrDisplay: _this._vrDisplay,
  12597. vrSupported: _this._vrSupported
  12598. };
  12599. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12600. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12601. };
  12602. if (!this._onVrDisplayConnect) {
  12603. this._onVrDisplayConnect = function (event) {
  12604. _this._vrDisplay = event.display;
  12605. notifyObservers();
  12606. };
  12607. this._onVrDisplayDisconnect = function () {
  12608. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12609. _this._vrDisplay = undefined;
  12610. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12611. notifyObservers();
  12612. };
  12613. this._onVrDisplayPresentChange = function () {
  12614. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12615. };
  12616. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12617. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12618. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12619. }
  12620. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12621. this._webVRInitPromise.then(notifyObservers);
  12622. return this._webVRInitPromise;
  12623. };
  12624. /**
  12625. * Call this function to switch to webVR mode
  12626. * Will do nothing if webVR is not supported or if there is no webVR device
  12627. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12628. */
  12629. Engine.prototype.enableVR = function () {
  12630. var _this = this;
  12631. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12632. var onResolved = function () {
  12633. _this.onVRRequestPresentComplete.notifyObservers(true);
  12634. _this._onVRFullScreenTriggered();
  12635. };
  12636. var onRejected = function () {
  12637. _this.onVRRequestPresentComplete.notifyObservers(false);
  12638. };
  12639. this.onVRRequestPresentStart.notifyObservers(this);
  12640. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12641. }
  12642. };
  12643. /**
  12644. * Call this function to leave webVR mode
  12645. * Will do nothing if webVR is not supported or if there is no webVR device
  12646. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12647. */
  12648. Engine.prototype.disableVR = function () {
  12649. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12650. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12651. }
  12652. };
  12653. Engine.prototype._getVRDisplaysAsync = function () {
  12654. var _this = this;
  12655. return new Promise(function (res, rej) {
  12656. if (navigator.getVRDisplays) {
  12657. navigator.getVRDisplays().then(function (devices) {
  12658. _this._vrSupported = true;
  12659. // note that devices may actually be an empty array. This is fine;
  12660. // we expect this._vrDisplay to be undefined in this case.
  12661. _this._vrDisplay = devices[0];
  12662. res({
  12663. vrDisplay: _this._vrDisplay,
  12664. vrSupported: _this._vrSupported
  12665. });
  12666. });
  12667. }
  12668. else {
  12669. _this._vrDisplay = undefined;
  12670. _this._vrSupported = false;
  12671. res({
  12672. vrDisplay: _this._vrDisplay,
  12673. vrSupported: _this._vrSupported
  12674. });
  12675. }
  12676. });
  12677. };
  12678. /**
  12679. * Binds the frame buffer to the specified texture.
  12680. * @param texture The texture to render to or null for the default canvas
  12681. * @param faceIndex The face of the texture to render to in case of cube texture
  12682. * @param requiredWidth The width of the target to render to
  12683. * @param requiredHeight The height of the target to render to
  12684. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12685. * @param depthStencilTexture The depth stencil texture to use to render
  12686. * @param lodLevel defines le lod level to bind to the frame buffer
  12687. */
  12688. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12689. if (lodLevel === void 0) { lodLevel = 0; }
  12690. if (this._currentRenderTarget) {
  12691. this.unBindFramebuffer(this._currentRenderTarget);
  12692. }
  12693. this._currentRenderTarget = texture;
  12694. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12695. var gl = this._gl;
  12696. if (texture.isCube) {
  12697. if (faceIndex === undefined) {
  12698. faceIndex = 0;
  12699. }
  12700. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12701. if (depthStencilTexture) {
  12702. if (depthStencilTexture._generateStencilBuffer) {
  12703. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12704. }
  12705. else {
  12706. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12707. }
  12708. }
  12709. }
  12710. if (this._cachedViewport && !forceFullscreenViewport) {
  12711. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12712. }
  12713. else {
  12714. if (!requiredWidth) {
  12715. requiredWidth = texture.width;
  12716. if (lodLevel) {
  12717. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12718. }
  12719. }
  12720. if (!requiredHeight) {
  12721. requiredHeight = texture.height;
  12722. if (lodLevel) {
  12723. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12724. }
  12725. }
  12726. this._viewport(0, 0, requiredWidth, requiredHeight);
  12727. }
  12728. this.wipeCaches();
  12729. };
  12730. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12731. if (this._currentFramebuffer !== framebuffer) {
  12732. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12733. this._currentFramebuffer = framebuffer;
  12734. }
  12735. };
  12736. /**
  12737. * Unbind the current render target texture from the webGL context
  12738. * @param texture defines the render target texture to unbind
  12739. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12740. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12741. */
  12742. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12743. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12744. this._currentRenderTarget = null;
  12745. // If MSAA, we need to bitblt back to main texture
  12746. var gl = this._gl;
  12747. if (texture._MSAAFramebuffer) {
  12748. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12749. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12750. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12751. }
  12752. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12753. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12754. gl.generateMipmap(gl.TEXTURE_2D);
  12755. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12756. }
  12757. if (onBeforeUnbind) {
  12758. if (texture._MSAAFramebuffer) {
  12759. // Bind the correct framebuffer
  12760. this.bindUnboundFramebuffer(texture._framebuffer);
  12761. }
  12762. onBeforeUnbind();
  12763. }
  12764. this.bindUnboundFramebuffer(null);
  12765. };
  12766. /**
  12767. * Unbind a list of render target textures from the webGL context
  12768. * This is used only when drawBuffer extension or webGL2 are active
  12769. * @param textures defines the render target textures to unbind
  12770. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12771. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12772. */
  12773. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12774. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12775. this._currentRenderTarget = null;
  12776. // If MSAA, we need to bitblt back to main texture
  12777. var gl = this._gl;
  12778. if (textures[0]._MSAAFramebuffer) {
  12779. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12780. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12781. var attachments = textures[0]._attachments;
  12782. if (!attachments) {
  12783. attachments = new Array(textures.length);
  12784. textures[0]._attachments = attachments;
  12785. }
  12786. for (var i = 0; i < textures.length; i++) {
  12787. var texture = textures[i];
  12788. for (var j = 0; j < attachments.length; j++) {
  12789. attachments[j] = gl.NONE;
  12790. }
  12791. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12792. gl.readBuffer(attachments[i]);
  12793. gl.drawBuffers(attachments);
  12794. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12795. }
  12796. for (var i = 0; i < attachments.length; i++) {
  12797. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12798. }
  12799. gl.drawBuffers(attachments);
  12800. }
  12801. for (var i = 0; i < textures.length; i++) {
  12802. var texture = textures[i];
  12803. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12804. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12805. gl.generateMipmap(gl.TEXTURE_2D);
  12806. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12807. }
  12808. }
  12809. if (onBeforeUnbind) {
  12810. if (textures[0]._MSAAFramebuffer) {
  12811. // Bind the correct framebuffer
  12812. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12813. }
  12814. onBeforeUnbind();
  12815. }
  12816. this.bindUnboundFramebuffer(null);
  12817. };
  12818. /**
  12819. * Force the mipmap generation for the given render target texture
  12820. * @param texture defines the render target texture to use
  12821. */
  12822. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12823. if (texture.generateMipMaps) {
  12824. var gl = this._gl;
  12825. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12826. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12827. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12828. }
  12829. };
  12830. /**
  12831. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12832. */
  12833. Engine.prototype.flushFramebuffer = function () {
  12834. this._gl.flush();
  12835. };
  12836. /**
  12837. * Unbind the current render target and bind the default framebuffer
  12838. */
  12839. Engine.prototype.restoreDefaultFramebuffer = function () {
  12840. if (this._currentRenderTarget) {
  12841. this.unBindFramebuffer(this._currentRenderTarget);
  12842. }
  12843. else {
  12844. this.bindUnboundFramebuffer(null);
  12845. }
  12846. if (this._cachedViewport) {
  12847. this.setViewport(this._cachedViewport);
  12848. }
  12849. this.wipeCaches();
  12850. };
  12851. // UBOs
  12852. /**
  12853. * Create an uniform buffer
  12854. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12855. * @param elements defines the content of the uniform buffer
  12856. * @returns the webGL uniform buffer
  12857. */
  12858. Engine.prototype.createUniformBuffer = function (elements) {
  12859. var ubo = this._gl.createBuffer();
  12860. if (!ubo) {
  12861. throw new Error("Unable to create uniform buffer");
  12862. }
  12863. this.bindUniformBuffer(ubo);
  12864. if (elements instanceof Float32Array) {
  12865. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12866. }
  12867. else {
  12868. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12869. }
  12870. this.bindUniformBuffer(null);
  12871. ubo.references = 1;
  12872. return ubo;
  12873. };
  12874. /**
  12875. * Create a dynamic uniform buffer
  12876. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12877. * @param elements defines the content of the uniform buffer
  12878. * @returns the webGL uniform buffer
  12879. */
  12880. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12881. var ubo = this._gl.createBuffer();
  12882. if (!ubo) {
  12883. throw new Error("Unable to create dynamic uniform buffer");
  12884. }
  12885. this.bindUniformBuffer(ubo);
  12886. if (elements instanceof Float32Array) {
  12887. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12888. }
  12889. else {
  12890. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12891. }
  12892. this.bindUniformBuffer(null);
  12893. ubo.references = 1;
  12894. return ubo;
  12895. };
  12896. /**
  12897. * Update an existing uniform buffer
  12898. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12899. * @param uniformBuffer defines the target uniform buffer
  12900. * @param elements defines the content to update
  12901. * @param offset defines the offset in the uniform buffer where update should start
  12902. * @param count defines the size of the data to update
  12903. */
  12904. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12905. this.bindUniformBuffer(uniformBuffer);
  12906. if (offset === undefined) {
  12907. offset = 0;
  12908. }
  12909. if (count === undefined) {
  12910. if (elements instanceof Float32Array) {
  12911. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12912. }
  12913. else {
  12914. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12915. }
  12916. }
  12917. else {
  12918. if (elements instanceof Float32Array) {
  12919. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12920. }
  12921. else {
  12922. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12923. }
  12924. }
  12925. this.bindUniformBuffer(null);
  12926. };
  12927. // VBOs
  12928. Engine.prototype._resetVertexBufferBinding = function () {
  12929. this.bindArrayBuffer(null);
  12930. this._cachedVertexBuffers = null;
  12931. };
  12932. /**
  12933. * Creates a vertex buffer
  12934. * @param data the data for the vertex buffer
  12935. * @returns the new WebGL static buffer
  12936. */
  12937. Engine.prototype.createVertexBuffer = function (data) {
  12938. var vbo = this._gl.createBuffer();
  12939. if (!vbo) {
  12940. throw new Error("Unable to create vertex buffer");
  12941. }
  12942. this.bindArrayBuffer(vbo);
  12943. if (data instanceof Array) {
  12944. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12945. }
  12946. else {
  12947. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12948. }
  12949. this._resetVertexBufferBinding();
  12950. vbo.references = 1;
  12951. return vbo;
  12952. };
  12953. /**
  12954. * Creates a dynamic vertex buffer
  12955. * @param data the data for the dynamic vertex buffer
  12956. * @returns the new WebGL dynamic buffer
  12957. */
  12958. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12959. var vbo = this._gl.createBuffer();
  12960. if (!vbo) {
  12961. throw new Error("Unable to create dynamic vertex buffer");
  12962. }
  12963. this.bindArrayBuffer(vbo);
  12964. if (data instanceof Array) {
  12965. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12966. }
  12967. else {
  12968. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12969. }
  12970. this._resetVertexBufferBinding();
  12971. vbo.references = 1;
  12972. return vbo;
  12973. };
  12974. /**
  12975. * Update a dynamic index buffer
  12976. * @param indexBuffer defines the target index buffer
  12977. * @param indices defines the data to update
  12978. * @param offset defines the offset in the target index buffer where update should start
  12979. */
  12980. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12981. if (offset === void 0) { offset = 0; }
  12982. // Force cache update
  12983. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12984. this.bindIndexBuffer(indexBuffer);
  12985. var arrayBuffer;
  12986. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12987. arrayBuffer = indices;
  12988. }
  12989. else {
  12990. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12991. }
  12992. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12993. this._resetIndexBufferBinding();
  12994. };
  12995. /**
  12996. * Updates a dynamic vertex buffer.
  12997. * @param vertexBuffer the vertex buffer to update
  12998. * @param data the data used to update the vertex buffer
  12999. * @param byteOffset the byte offset of the data
  13000. * @param byteLength the byte length of the data
  13001. */
  13002. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13003. this.bindArrayBuffer(vertexBuffer);
  13004. if (byteOffset === undefined) {
  13005. byteOffset = 0;
  13006. }
  13007. if (byteLength === undefined) {
  13008. if (data instanceof Array) {
  13009. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13010. }
  13011. else {
  13012. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13013. }
  13014. }
  13015. else {
  13016. if (data instanceof Array) {
  13017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13018. }
  13019. else {
  13020. if (data instanceof ArrayBuffer) {
  13021. data = new Uint8Array(data, byteOffset, byteLength);
  13022. }
  13023. else {
  13024. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13025. }
  13026. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13027. }
  13028. }
  13029. this._resetVertexBufferBinding();
  13030. };
  13031. Engine.prototype._resetIndexBufferBinding = function () {
  13032. this.bindIndexBuffer(null);
  13033. this._cachedIndexBuffer = null;
  13034. };
  13035. /**
  13036. * Creates a new index buffer
  13037. * @param indices defines the content of the index buffer
  13038. * @param updatable defines if the index buffer must be updatable
  13039. * @returns a new webGL buffer
  13040. */
  13041. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13042. var vbo = this._gl.createBuffer();
  13043. if (!vbo) {
  13044. throw new Error("Unable to create index buffer");
  13045. }
  13046. this.bindIndexBuffer(vbo);
  13047. // Check for 32 bits indices
  13048. var arrayBuffer;
  13049. var need32Bits = false;
  13050. if (indices instanceof Uint16Array) {
  13051. arrayBuffer = indices;
  13052. }
  13053. else {
  13054. //check 32 bit support
  13055. if (this._caps.uintIndices) {
  13056. if (indices instanceof Uint32Array) {
  13057. arrayBuffer = indices;
  13058. need32Bits = true;
  13059. }
  13060. else {
  13061. //number[] or Int32Array, check if 32 bit is necessary
  13062. for (var index = 0; index < indices.length; index++) {
  13063. if (indices[index] > 65535) {
  13064. need32Bits = true;
  13065. break;
  13066. }
  13067. }
  13068. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13069. }
  13070. }
  13071. else {
  13072. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13073. arrayBuffer = new Uint16Array(indices);
  13074. }
  13075. }
  13076. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13077. this._resetIndexBufferBinding();
  13078. vbo.references = 1;
  13079. vbo.is32Bits = need32Bits;
  13080. return vbo;
  13081. };
  13082. /**
  13083. * Bind a webGL buffer to the webGL context
  13084. * @param buffer defines the buffer to bind
  13085. */
  13086. Engine.prototype.bindArrayBuffer = function (buffer) {
  13087. if (!this._vaoRecordInProgress) {
  13088. this._unbindVertexArrayObject();
  13089. }
  13090. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13091. };
  13092. /**
  13093. * Bind an uniform buffer to the current webGL context
  13094. * @param buffer defines the buffer to bind
  13095. */
  13096. Engine.prototype.bindUniformBuffer = function (buffer) {
  13097. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13098. };
  13099. /**
  13100. * Bind a buffer to the current webGL context at a given location
  13101. * @param buffer defines the buffer to bind
  13102. * @param location defines the index where to bind the buffer
  13103. */
  13104. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13105. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13106. };
  13107. /**
  13108. * Bind a specific block at a given index in a specific shader program
  13109. * @param shaderProgram defines the shader program
  13110. * @param blockName defines the block name
  13111. * @param index defines the index where to bind the block
  13112. */
  13113. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13114. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13115. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13116. };
  13117. ;
  13118. Engine.prototype.bindIndexBuffer = function (buffer) {
  13119. if (!this._vaoRecordInProgress) {
  13120. this._unbindVertexArrayObject();
  13121. }
  13122. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13123. };
  13124. Engine.prototype.bindBuffer = function (buffer, target) {
  13125. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13126. this._gl.bindBuffer(target, buffer);
  13127. this._currentBoundBuffer[target] = buffer;
  13128. }
  13129. };
  13130. /**
  13131. * update the bound buffer with the given data
  13132. * @param data defines the data to update
  13133. */
  13134. Engine.prototype.updateArrayBuffer = function (data) {
  13135. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13136. };
  13137. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13138. var pointer = this._currentBufferPointers[indx];
  13139. var changed = false;
  13140. if (!pointer.active) {
  13141. changed = true;
  13142. pointer.active = true;
  13143. pointer.index = indx;
  13144. pointer.size = size;
  13145. pointer.type = type;
  13146. pointer.normalized = normalized;
  13147. pointer.stride = stride;
  13148. pointer.offset = offset;
  13149. pointer.buffer = buffer;
  13150. }
  13151. else {
  13152. if (pointer.buffer !== buffer) {
  13153. pointer.buffer = buffer;
  13154. changed = true;
  13155. }
  13156. if (pointer.size !== size) {
  13157. pointer.size = size;
  13158. changed = true;
  13159. }
  13160. if (pointer.type !== type) {
  13161. pointer.type = type;
  13162. changed = true;
  13163. }
  13164. if (pointer.normalized !== normalized) {
  13165. pointer.normalized = normalized;
  13166. changed = true;
  13167. }
  13168. if (pointer.stride !== stride) {
  13169. pointer.stride = stride;
  13170. changed = true;
  13171. }
  13172. if (pointer.offset !== offset) {
  13173. pointer.offset = offset;
  13174. changed = true;
  13175. }
  13176. }
  13177. if (changed || this._vaoRecordInProgress) {
  13178. this.bindArrayBuffer(buffer);
  13179. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13180. }
  13181. };
  13182. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13183. if (indexBuffer == null) {
  13184. return;
  13185. }
  13186. if (this._cachedIndexBuffer !== indexBuffer) {
  13187. this._cachedIndexBuffer = indexBuffer;
  13188. this.bindIndexBuffer(indexBuffer);
  13189. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13190. }
  13191. };
  13192. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13193. var attributes = effect.getAttributesNames();
  13194. if (!this._vaoRecordInProgress) {
  13195. this._unbindVertexArrayObject();
  13196. }
  13197. this.unbindAllAttributes();
  13198. for (var index = 0; index < attributes.length; index++) {
  13199. var order = effect.getAttributeLocation(index);
  13200. if (order >= 0) {
  13201. var vertexBuffer = vertexBuffers[attributes[index]];
  13202. if (!vertexBuffer) {
  13203. continue;
  13204. }
  13205. this._gl.enableVertexAttribArray(order);
  13206. if (!this._vaoRecordInProgress) {
  13207. this._vertexAttribArraysEnabled[order] = true;
  13208. }
  13209. var buffer = vertexBuffer.getBuffer();
  13210. if (buffer) {
  13211. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13212. if (vertexBuffer.getIsInstanced()) {
  13213. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13214. if (!this._vaoRecordInProgress) {
  13215. this._currentInstanceLocations.push(order);
  13216. this._currentInstanceBuffers.push(buffer);
  13217. }
  13218. }
  13219. }
  13220. }
  13221. }
  13222. };
  13223. /**
  13224. * Records a vertex array object
  13225. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13226. * @param vertexBuffers defines the list of vertex buffers to store
  13227. * @param indexBuffer defines the index buffer to store
  13228. * @param effect defines the effect to store
  13229. * @returns the new vertex array object
  13230. */
  13231. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13232. var vao = this._gl.createVertexArray();
  13233. this._vaoRecordInProgress = true;
  13234. this._gl.bindVertexArray(vao);
  13235. this._mustWipeVertexAttributes = true;
  13236. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13237. this.bindIndexBuffer(indexBuffer);
  13238. this._vaoRecordInProgress = false;
  13239. this._gl.bindVertexArray(null);
  13240. return vao;
  13241. };
  13242. /**
  13243. * Bind a specific vertex array object
  13244. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13245. * @param vertexArrayObject defines the vertex array object to bind
  13246. * @param indexBuffer defines the index buffer to bind
  13247. */
  13248. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13249. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13250. this._cachedVertexArrayObject = vertexArrayObject;
  13251. this._gl.bindVertexArray(vertexArrayObject);
  13252. this._cachedVertexBuffers = null;
  13253. this._cachedIndexBuffer = null;
  13254. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13255. this._mustWipeVertexAttributes = true;
  13256. }
  13257. };
  13258. /**
  13259. * Bind webGl buffers directly to the webGL context
  13260. * @param vertexBuffer defines the vertex buffer to bind
  13261. * @param indexBuffer defines the index buffer to bind
  13262. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13263. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13264. * @param effect defines the effect associated with the vertex buffer
  13265. */
  13266. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13267. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13268. this._cachedVertexBuffers = vertexBuffer;
  13269. this._cachedEffectForVertexBuffers = effect;
  13270. var attributesCount = effect.getAttributesCount();
  13271. this._unbindVertexArrayObject();
  13272. this.unbindAllAttributes();
  13273. var offset = 0;
  13274. for (var index = 0; index < attributesCount; index++) {
  13275. if (index < vertexDeclaration.length) {
  13276. var order = effect.getAttributeLocation(index);
  13277. if (order >= 0) {
  13278. this._gl.enableVertexAttribArray(order);
  13279. this._vertexAttribArraysEnabled[order] = true;
  13280. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13281. }
  13282. offset += vertexDeclaration[index] * 4;
  13283. }
  13284. }
  13285. }
  13286. this._bindIndexBufferWithCache(indexBuffer);
  13287. };
  13288. Engine.prototype._unbindVertexArrayObject = function () {
  13289. if (!this._cachedVertexArrayObject) {
  13290. return;
  13291. }
  13292. this._cachedVertexArrayObject = null;
  13293. this._gl.bindVertexArray(null);
  13294. };
  13295. /**
  13296. * Bind a list of vertex buffers to the webGL context
  13297. * @param vertexBuffers defines the list of vertex buffers to bind
  13298. * @param indexBuffer defines the index buffer to bind
  13299. * @param effect defines the effect associated with the vertex buffers
  13300. */
  13301. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13302. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13303. this._cachedVertexBuffers = vertexBuffers;
  13304. this._cachedEffectForVertexBuffers = effect;
  13305. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13306. }
  13307. this._bindIndexBufferWithCache(indexBuffer);
  13308. };
  13309. /**
  13310. * Unbind all instance attributes
  13311. */
  13312. Engine.prototype.unbindInstanceAttributes = function () {
  13313. var boundBuffer;
  13314. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13315. var instancesBuffer = this._currentInstanceBuffers[i];
  13316. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13317. boundBuffer = instancesBuffer;
  13318. this.bindArrayBuffer(instancesBuffer);
  13319. }
  13320. var offsetLocation = this._currentInstanceLocations[i];
  13321. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13322. }
  13323. this._currentInstanceBuffers.length = 0;
  13324. this._currentInstanceLocations.length = 0;
  13325. };
  13326. /**
  13327. * Release and free the memory of a vertex array object
  13328. * @param vao defines the vertex array object to delete
  13329. */
  13330. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13331. this._gl.deleteVertexArray(vao);
  13332. };
  13333. /** @hidden */
  13334. Engine.prototype._releaseBuffer = function (buffer) {
  13335. buffer.references--;
  13336. if (buffer.references === 0) {
  13337. this._gl.deleteBuffer(buffer);
  13338. return true;
  13339. }
  13340. return false;
  13341. };
  13342. /**
  13343. * Creates a webGL buffer to use with instanciation
  13344. * @param capacity defines the size of the buffer
  13345. * @returns the webGL buffer
  13346. */
  13347. Engine.prototype.createInstancesBuffer = function (capacity) {
  13348. var buffer = this._gl.createBuffer();
  13349. if (!buffer) {
  13350. throw new Error("Unable to create instance buffer");
  13351. }
  13352. buffer.capacity = capacity;
  13353. this.bindArrayBuffer(buffer);
  13354. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13355. return buffer;
  13356. };
  13357. /**
  13358. * Delete a webGL buffer used with instanciation
  13359. * @param buffer defines the webGL buffer to delete
  13360. */
  13361. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13362. this._gl.deleteBuffer(buffer);
  13363. };
  13364. /**
  13365. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13366. * @param instancesBuffer defines the webGL buffer to update and bind
  13367. * @param data defines the data to store in the buffer
  13368. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13369. */
  13370. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13371. this.bindArrayBuffer(instancesBuffer);
  13372. if (data) {
  13373. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13374. }
  13375. if (offsetLocations[0].index !== undefined) {
  13376. var stride = 0;
  13377. for (var i = 0; i < offsetLocations.length; i++) {
  13378. var ai = offsetLocations[i];
  13379. stride += ai.attributeSize * 4;
  13380. }
  13381. for (var i = 0; i < offsetLocations.length; i++) {
  13382. var ai = offsetLocations[i];
  13383. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13384. this._gl.enableVertexAttribArray(ai.index);
  13385. this._vertexAttribArraysEnabled[ai.index] = true;
  13386. }
  13387. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13388. this._gl.vertexAttribDivisor(ai.index, 1);
  13389. this._currentInstanceLocations.push(ai.index);
  13390. this._currentInstanceBuffers.push(instancesBuffer);
  13391. }
  13392. }
  13393. else {
  13394. for (var index = 0; index < 4; index++) {
  13395. var offsetLocation = offsetLocations[index];
  13396. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13397. this._gl.enableVertexAttribArray(offsetLocation);
  13398. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13399. }
  13400. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13401. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13402. this._currentInstanceLocations.push(offsetLocation);
  13403. this._currentInstanceBuffers.push(instancesBuffer);
  13404. }
  13405. }
  13406. };
  13407. /**
  13408. * Apply all cached states (depth, culling, stencil and alpha)
  13409. */
  13410. Engine.prototype.applyStates = function () {
  13411. this._depthCullingState.apply(this._gl);
  13412. this._stencilState.apply(this._gl);
  13413. this._alphaState.apply(this._gl);
  13414. };
  13415. /**
  13416. * Send a draw order
  13417. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13418. * @param indexStart defines the starting index
  13419. * @param indexCount defines the number of index to draw
  13420. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13421. */
  13422. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13423. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13424. };
  13425. /**
  13426. * Draw a list of points
  13427. * @param verticesStart defines the index of first vertex to draw
  13428. * @param verticesCount defines the count of vertices to draw
  13429. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13430. */
  13431. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13432. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13433. };
  13434. /**
  13435. * Draw a list of unindexed primitives
  13436. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13437. * @param verticesStart defines the index of first vertex to draw
  13438. * @param verticesCount defines the count of vertices to draw
  13439. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13440. */
  13441. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13442. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13443. };
  13444. /**
  13445. * Draw a list of indexed primitives
  13446. * @param fillMode defines the primitive to use
  13447. * @param indexStart defines the starting index
  13448. * @param indexCount defines the number of index to draw
  13449. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13450. */
  13451. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13452. // Apply states
  13453. this.applyStates();
  13454. this._drawCalls.addCount(1, false);
  13455. // Render
  13456. var drawMode = this._drawMode(fillMode);
  13457. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13458. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13459. if (instancesCount) {
  13460. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13461. }
  13462. else {
  13463. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13464. }
  13465. };
  13466. /**
  13467. * Draw a list of unindexed primitives
  13468. * @param fillMode defines the primitive to use
  13469. * @param verticesStart defines the index of first vertex to draw
  13470. * @param verticesCount defines the count of vertices to draw
  13471. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13472. */
  13473. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13474. // Apply states
  13475. this.applyStates();
  13476. this._drawCalls.addCount(1, false);
  13477. var drawMode = this._drawMode(fillMode);
  13478. if (instancesCount) {
  13479. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13480. }
  13481. else {
  13482. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13483. }
  13484. };
  13485. Engine.prototype._drawMode = function (fillMode) {
  13486. switch (fillMode) {
  13487. // Triangle views
  13488. case BABYLON.Material.TriangleFillMode:
  13489. return this._gl.TRIANGLES;
  13490. case BABYLON.Material.PointFillMode:
  13491. return this._gl.POINTS;
  13492. case BABYLON.Material.WireFrameFillMode:
  13493. return this._gl.LINES;
  13494. // Draw modes
  13495. case BABYLON.Material.PointListDrawMode:
  13496. return this._gl.POINTS;
  13497. case BABYLON.Material.LineListDrawMode:
  13498. return this._gl.LINES;
  13499. case BABYLON.Material.LineLoopDrawMode:
  13500. return this._gl.LINE_LOOP;
  13501. case BABYLON.Material.LineStripDrawMode:
  13502. return this._gl.LINE_STRIP;
  13503. case BABYLON.Material.TriangleStripDrawMode:
  13504. return this._gl.TRIANGLE_STRIP;
  13505. case BABYLON.Material.TriangleFanDrawMode:
  13506. return this._gl.TRIANGLE_FAN;
  13507. default:
  13508. return this._gl.TRIANGLES;
  13509. }
  13510. };
  13511. // Shaders
  13512. /** @hidden */
  13513. Engine.prototype._releaseEffect = function (effect) {
  13514. if (this._compiledEffects[effect._key]) {
  13515. delete this._compiledEffects[effect._key];
  13516. this._deleteProgram(effect.getProgram());
  13517. }
  13518. };
  13519. /** @hidden */
  13520. Engine.prototype._deleteProgram = function (program) {
  13521. if (program) {
  13522. program.__SPECTOR_rebuildProgram = null;
  13523. if (program.transformFeedback) {
  13524. this.deleteTransformFeedback(program.transformFeedback);
  13525. program.transformFeedback = null;
  13526. }
  13527. this._gl.deleteProgram(program);
  13528. }
  13529. };
  13530. /**
  13531. * Create a new effect (used to store vertex/fragment shaders)
  13532. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13533. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13534. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13535. * @param samplers defines an array of string used to represent textures
  13536. * @param defines defines the string containing the defines to use to compile the shaders
  13537. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13538. * @param onCompiled defines a function to call when the effect creation is successful
  13539. * @param onError defines a function to call when the effect creation has failed
  13540. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13541. * @returns the new Effect
  13542. */
  13543. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13544. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13545. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13546. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13547. if (this._compiledEffects[name]) {
  13548. var compiledEffect = this._compiledEffects[name];
  13549. if (onCompiled && compiledEffect.isReady()) {
  13550. onCompiled(compiledEffect);
  13551. }
  13552. return compiledEffect;
  13553. }
  13554. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13555. effect._key = name;
  13556. this._compiledEffects[name] = effect;
  13557. return effect;
  13558. };
  13559. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13560. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13561. };
  13562. ;
  13563. Engine.prototype._compileRawShader = function (source, type) {
  13564. var gl = this._gl;
  13565. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13566. gl.shaderSource(shader, source);
  13567. gl.compileShader(shader);
  13568. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13569. var log = gl.getShaderInfoLog(shader);
  13570. if (log) {
  13571. throw new Error(log);
  13572. }
  13573. }
  13574. if (!shader) {
  13575. throw new Error("Something went wrong while compile the shader.");
  13576. }
  13577. return shader;
  13578. };
  13579. ;
  13580. /**
  13581. * Directly creates a webGL program
  13582. * @param vertexCode defines the vertex shader code to use
  13583. * @param fragmentCode defines the fragment shader code to use
  13584. * @param context defines the webGL context to use (if not set, the current one will be used)
  13585. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13586. * @returns the new webGL program
  13587. */
  13588. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13589. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13590. context = context || this._gl;
  13591. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13592. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13593. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13594. };
  13595. /**
  13596. * Creates a webGL program
  13597. * @param vertexCode defines the vertex shader code to use
  13598. * @param fragmentCode defines the fragment shader code to use
  13599. * @param defines defines the string containing the defines to use to compile the shaders
  13600. * @param context defines the webGL context to use (if not set, the current one will be used)
  13601. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13602. * @returns the new webGL program
  13603. */
  13604. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13605. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13606. context = context || this._gl;
  13607. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13608. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13609. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13610. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13611. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13612. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13613. return program;
  13614. };
  13615. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13616. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13617. var shaderProgram = context.createProgram();
  13618. if (!shaderProgram) {
  13619. throw new Error("Unable to create program");
  13620. }
  13621. context.attachShader(shaderProgram, vertexShader);
  13622. context.attachShader(shaderProgram, fragmentShader);
  13623. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13624. var transformFeedback = this.createTransformFeedback();
  13625. this.bindTransformFeedback(transformFeedback);
  13626. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13627. shaderProgram.transformFeedback = transformFeedback;
  13628. }
  13629. context.linkProgram(shaderProgram);
  13630. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13631. this.bindTransformFeedback(null);
  13632. }
  13633. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13634. if (!linked) {
  13635. var error = context.getProgramInfoLog(shaderProgram);
  13636. if (error) {
  13637. throw new Error(error);
  13638. }
  13639. }
  13640. if (this.validateShaderPrograms) {
  13641. context.validateProgram(shaderProgram);
  13642. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13643. if (!validated) {
  13644. var error = context.getProgramInfoLog(shaderProgram);
  13645. if (error) {
  13646. throw new Error(error);
  13647. }
  13648. }
  13649. }
  13650. context.deleteShader(vertexShader);
  13651. context.deleteShader(fragmentShader);
  13652. return shaderProgram;
  13653. };
  13654. /**
  13655. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13656. * @param shaderProgram defines the webGL program to use
  13657. * @param uniformsNames defines the list of uniform names
  13658. * @returns an array of webGL uniform locations
  13659. */
  13660. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13661. var results = new Array();
  13662. for (var index = 0; index < uniformsNames.length; index++) {
  13663. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13664. }
  13665. return results;
  13666. };
  13667. /**
  13668. * Gets the lsit of active attributes for a given webGL program
  13669. * @param shaderProgram defines the webGL program to use
  13670. * @param attributesNames defines the list of attribute names to get
  13671. * @returns an array of indices indicating the offset of each attribute
  13672. */
  13673. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13674. var results = [];
  13675. for (var index = 0; index < attributesNames.length; index++) {
  13676. try {
  13677. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13678. }
  13679. catch (e) {
  13680. results.push(-1);
  13681. }
  13682. }
  13683. return results;
  13684. };
  13685. /**
  13686. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13687. * @param effect defines the effect to activate
  13688. */
  13689. Engine.prototype.enableEffect = function (effect) {
  13690. if (!effect) {
  13691. return;
  13692. }
  13693. // Use program
  13694. this.bindSamplers(effect);
  13695. this._currentEffect = effect;
  13696. if (effect.onBind) {
  13697. effect.onBind(effect);
  13698. }
  13699. effect.onBindObservable.notifyObservers(effect);
  13700. };
  13701. /**
  13702. * Set the value of an uniform to an array of int32
  13703. * @param uniform defines the webGL uniform location where to store the value
  13704. * @param array defines the array of int32 to store
  13705. */
  13706. Engine.prototype.setIntArray = function (uniform, array) {
  13707. if (!uniform)
  13708. return;
  13709. this._gl.uniform1iv(uniform, array);
  13710. };
  13711. /**
  13712. * Set the value of an uniform to an array of int32 (stored as vec2)
  13713. * @param uniform defines the webGL uniform location where to store the value
  13714. * @param array defines the array of int32 to store
  13715. */
  13716. Engine.prototype.setIntArray2 = function (uniform, array) {
  13717. if (!uniform || array.length % 2 !== 0)
  13718. return;
  13719. this._gl.uniform2iv(uniform, array);
  13720. };
  13721. /**
  13722. * Set the value of an uniform to an array of int32 (stored as vec3)
  13723. * @param uniform defines the webGL uniform location where to store the value
  13724. * @param array defines the array of int32 to store
  13725. */
  13726. Engine.prototype.setIntArray3 = function (uniform, array) {
  13727. if (!uniform || array.length % 3 !== 0)
  13728. return;
  13729. this._gl.uniform3iv(uniform, array);
  13730. };
  13731. /**
  13732. * Set the value of an uniform to an array of int32 (stored as vec4)
  13733. * @param uniform defines the webGL uniform location where to store the value
  13734. * @param array defines the array of int32 to store
  13735. */
  13736. Engine.prototype.setIntArray4 = function (uniform, array) {
  13737. if (!uniform || array.length % 4 !== 0)
  13738. return;
  13739. this._gl.uniform4iv(uniform, array);
  13740. };
  13741. /**
  13742. * Set the value of an uniform to an array of float32
  13743. * @param uniform defines the webGL uniform location where to store the value
  13744. * @param array defines the array of float32 to store
  13745. */
  13746. Engine.prototype.setFloatArray = function (uniform, array) {
  13747. if (!uniform)
  13748. return;
  13749. this._gl.uniform1fv(uniform, array);
  13750. };
  13751. /**
  13752. * Set the value of an uniform to an array of float32 (stored as vec2)
  13753. * @param uniform defines the webGL uniform location where to store the value
  13754. * @param array defines the array of float32 to store
  13755. */
  13756. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13757. if (!uniform || array.length % 2 !== 0)
  13758. return;
  13759. this._gl.uniform2fv(uniform, array);
  13760. };
  13761. /**
  13762. * Set the value of an uniform to an array of float32 (stored as vec3)
  13763. * @param uniform defines the webGL uniform location where to store the value
  13764. * @param array defines the array of float32 to store
  13765. */
  13766. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13767. if (!uniform || array.length % 3 !== 0)
  13768. return;
  13769. this._gl.uniform3fv(uniform, array);
  13770. };
  13771. /**
  13772. * Set the value of an uniform to an array of float32 (stored as vec4)
  13773. * @param uniform defines the webGL uniform location where to store the value
  13774. * @param array defines the array of float32 to store
  13775. */
  13776. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13777. if (!uniform || array.length % 4 !== 0)
  13778. return;
  13779. this._gl.uniform4fv(uniform, array);
  13780. };
  13781. /**
  13782. * Set the value of an uniform to an array of number
  13783. * @param uniform defines the webGL uniform location where to store the value
  13784. * @param array defines the array of number to store
  13785. */
  13786. Engine.prototype.setArray = function (uniform, array) {
  13787. if (!uniform)
  13788. return;
  13789. this._gl.uniform1fv(uniform, array);
  13790. };
  13791. /**
  13792. * Set the value of an uniform to an array of number (stored as vec2)
  13793. * @param uniform defines the webGL uniform location where to store the value
  13794. * @param array defines the array of number to store
  13795. */
  13796. Engine.prototype.setArray2 = function (uniform, array) {
  13797. if (!uniform || array.length % 2 !== 0)
  13798. return;
  13799. this._gl.uniform2fv(uniform, array);
  13800. };
  13801. /**
  13802. * Set the value of an uniform to an array of number (stored as vec3)
  13803. * @param uniform defines the webGL uniform location where to store the value
  13804. * @param array defines the array of number to store
  13805. */
  13806. Engine.prototype.setArray3 = function (uniform, array) {
  13807. if (!uniform || array.length % 3 !== 0)
  13808. return;
  13809. this._gl.uniform3fv(uniform, array);
  13810. };
  13811. /**
  13812. * Set the value of an uniform to an array of number (stored as vec4)
  13813. * @param uniform defines the webGL uniform location where to store the value
  13814. * @param array defines the array of number to store
  13815. */
  13816. Engine.prototype.setArray4 = function (uniform, array) {
  13817. if (!uniform || array.length % 4 !== 0)
  13818. return;
  13819. this._gl.uniform4fv(uniform, array);
  13820. };
  13821. /**
  13822. * Set the value of an uniform to an array of float32 (stored as matrices)
  13823. * @param uniform defines the webGL uniform location where to store the value
  13824. * @param matrices defines the array of float32 to store
  13825. */
  13826. Engine.prototype.setMatrices = function (uniform, matrices) {
  13827. if (!uniform)
  13828. return;
  13829. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13830. };
  13831. /**
  13832. * Set the value of an uniform to a matrix
  13833. * @param uniform defines the webGL uniform location where to store the value
  13834. * @param matrix defines the matrix to store
  13835. */
  13836. Engine.prototype.setMatrix = function (uniform, matrix) {
  13837. if (!uniform)
  13838. return;
  13839. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13840. };
  13841. /**
  13842. * Set the value of an uniform to a matrix (3x3)
  13843. * @param uniform defines the webGL uniform location where to store the value
  13844. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13845. */
  13846. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13847. if (!uniform)
  13848. return;
  13849. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13850. };
  13851. /**
  13852. * Set the value of an uniform to a matrix (2x2)
  13853. * @param uniform defines the webGL uniform location where to store the value
  13854. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13855. */
  13856. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13857. if (!uniform)
  13858. return;
  13859. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13860. };
  13861. /**
  13862. * Set the value of an uniform to a number (int)
  13863. * @param uniform defines the webGL uniform location where to store the value
  13864. * @param value defines the int number to store
  13865. */
  13866. Engine.prototype.setInt = function (uniform, value) {
  13867. if (!uniform)
  13868. return;
  13869. this._gl.uniform1i(uniform, value);
  13870. };
  13871. /**
  13872. * Set the value of an uniform to a number (float)
  13873. * @param uniform defines the webGL uniform location where to store the value
  13874. * @param value defines the float number to store
  13875. */
  13876. Engine.prototype.setFloat = function (uniform, value) {
  13877. if (!uniform)
  13878. return;
  13879. this._gl.uniform1f(uniform, value);
  13880. };
  13881. /**
  13882. * Set the value of an uniform to a vec2
  13883. * @param uniform defines the webGL uniform location where to store the value
  13884. * @param x defines the 1st component of the value
  13885. * @param y defines the 2nd component of the value
  13886. */
  13887. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13888. if (!uniform)
  13889. return;
  13890. this._gl.uniform2f(uniform, x, y);
  13891. };
  13892. /**
  13893. * Set the value of an uniform to a vec3
  13894. * @param uniform defines the webGL uniform location where to store the value
  13895. * @param x defines the 1st component of the value
  13896. * @param y defines the 2nd component of the value
  13897. * @param z defines the 3rd component of the value
  13898. */
  13899. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13900. if (!uniform)
  13901. return;
  13902. this._gl.uniform3f(uniform, x, y, z);
  13903. };
  13904. /**
  13905. * Set the value of an uniform to a boolean
  13906. * @param uniform defines the webGL uniform location where to store the value
  13907. * @param bool defines the boolean to store
  13908. */
  13909. Engine.prototype.setBool = function (uniform, bool) {
  13910. if (!uniform)
  13911. return;
  13912. this._gl.uniform1i(uniform, bool);
  13913. };
  13914. /**
  13915. * Set the value of an uniform to a vec4
  13916. * @param uniform defines the webGL uniform location where to store the value
  13917. * @param x defines the 1st component of the value
  13918. * @param y defines the 2nd component of the value
  13919. * @param z defines the 3rd component of the value
  13920. * @param w defines the 4th component of the value
  13921. */
  13922. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13923. if (!uniform)
  13924. return;
  13925. this._gl.uniform4f(uniform, x, y, z, w);
  13926. };
  13927. /**
  13928. * Set the value of an uniform to a Color3
  13929. * @param uniform defines the webGL uniform location where to store the value
  13930. * @param color3 defines the color to store
  13931. */
  13932. Engine.prototype.setColor3 = function (uniform, color3) {
  13933. if (!uniform)
  13934. return;
  13935. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13936. };
  13937. /**
  13938. * Set the value of an uniform to a Color3 and an alpha value
  13939. * @param uniform defines the webGL uniform location where to store the value
  13940. * @param color3 defines the color to store
  13941. * @param alpha defines the alpha component to store
  13942. */
  13943. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13944. if (!uniform)
  13945. return;
  13946. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13947. };
  13948. /**
  13949. * Sets a Color4 on a uniform variable
  13950. * @param uniform defines the uniform location
  13951. * @param color4 defines the value to be set
  13952. */
  13953. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13954. if (!uniform)
  13955. return;
  13956. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13957. };
  13958. // States
  13959. /**
  13960. * Set various states to the webGL context
  13961. * @param culling defines backface culling state
  13962. * @param zOffset defines the value to apply to zOffset (0 by default)
  13963. * @param force defines if states must be applied even if cache is up to date
  13964. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13965. */
  13966. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13967. if (zOffset === void 0) { zOffset = 0; }
  13968. if (reverseSide === void 0) { reverseSide = false; }
  13969. // Culling
  13970. if (this._depthCullingState.cull !== culling || force) {
  13971. this._depthCullingState.cull = culling;
  13972. }
  13973. // Cull face
  13974. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13975. if (this._depthCullingState.cullFace !== cullFace || force) {
  13976. this._depthCullingState.cullFace = cullFace;
  13977. }
  13978. // Z offset
  13979. this.setZOffset(zOffset);
  13980. // Front face
  13981. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13982. if (this._depthCullingState.frontFace !== frontFace || force) {
  13983. this._depthCullingState.frontFace = frontFace;
  13984. }
  13985. };
  13986. /**
  13987. * Set the z offset to apply to current rendering
  13988. * @param value defines the offset to apply
  13989. */
  13990. Engine.prototype.setZOffset = function (value) {
  13991. this._depthCullingState.zOffset = value;
  13992. };
  13993. /**
  13994. * Gets the current value of the zOffset
  13995. * @returns the current zOffset state
  13996. */
  13997. Engine.prototype.getZOffset = function () {
  13998. return this._depthCullingState.zOffset;
  13999. };
  14000. /**
  14001. * Enable or disable depth buffering
  14002. * @param enable defines the state to set
  14003. */
  14004. Engine.prototype.setDepthBuffer = function (enable) {
  14005. this._depthCullingState.depthTest = enable;
  14006. };
  14007. /**
  14008. * Gets a boolean indicating if depth writing is enabled
  14009. * @returns the current depth writing state
  14010. */
  14011. Engine.prototype.getDepthWrite = function () {
  14012. return this._depthCullingState.depthMask;
  14013. };
  14014. /**
  14015. * Enable or disable depth writing
  14016. * @param enable defines the state to set
  14017. */
  14018. Engine.prototype.setDepthWrite = function (enable) {
  14019. this._depthCullingState.depthMask = enable;
  14020. };
  14021. /**
  14022. * Enable or disable color writing
  14023. * @param enable defines the state to set
  14024. */
  14025. Engine.prototype.setColorWrite = function (enable) {
  14026. this._gl.colorMask(enable, enable, enable, enable);
  14027. this._colorWrite = enable;
  14028. };
  14029. /**
  14030. * Gets a boolean indicating if color writing is enabled
  14031. * @returns the current color writing state
  14032. */
  14033. Engine.prototype.getColorWrite = function () {
  14034. return this._colorWrite;
  14035. };
  14036. /**
  14037. * Sets alpha constants used by some alpha blending modes
  14038. * @param r defines the red component
  14039. * @param g defines the green component
  14040. * @param b defines the blue component
  14041. * @param a defines the alpha component
  14042. */
  14043. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14044. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14045. };
  14046. /**
  14047. * Sets the current alpha mode
  14048. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14049. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14050. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14051. */
  14052. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14053. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14054. if (this._alphaMode === mode) {
  14055. return;
  14056. }
  14057. switch (mode) {
  14058. case Engine.ALPHA_DISABLE:
  14059. this._alphaState.alphaBlend = false;
  14060. break;
  14061. case Engine.ALPHA_PREMULTIPLIED:
  14062. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14063. this._alphaState.alphaBlend = true;
  14064. break;
  14065. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14066. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14067. this._alphaState.alphaBlend = true;
  14068. break;
  14069. case Engine.ALPHA_COMBINE:
  14070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14071. this._alphaState.alphaBlend = true;
  14072. break;
  14073. case Engine.ALPHA_ONEONE:
  14074. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14075. this._alphaState.alphaBlend = true;
  14076. break;
  14077. case Engine.ALPHA_ADD:
  14078. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14079. this._alphaState.alphaBlend = true;
  14080. break;
  14081. case Engine.ALPHA_SUBTRACT:
  14082. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14083. this._alphaState.alphaBlend = true;
  14084. break;
  14085. case Engine.ALPHA_MULTIPLY:
  14086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14087. this._alphaState.alphaBlend = true;
  14088. break;
  14089. case Engine.ALPHA_MAXIMIZED:
  14090. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14091. this._alphaState.alphaBlend = true;
  14092. break;
  14093. case Engine.ALPHA_INTERPOLATE:
  14094. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14095. this._alphaState.alphaBlend = true;
  14096. break;
  14097. case Engine.ALPHA_SCREENMODE:
  14098. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14099. this._alphaState.alphaBlend = true;
  14100. break;
  14101. }
  14102. if (!noDepthWriteChange) {
  14103. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14104. }
  14105. this._alphaMode = mode;
  14106. };
  14107. /**
  14108. * Gets the current alpha mode
  14109. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14110. * @returns the current alpha mode
  14111. */
  14112. Engine.prototype.getAlphaMode = function () {
  14113. return this._alphaMode;
  14114. };
  14115. // Textures
  14116. /**
  14117. * Clears the list of texture accessible through engine.
  14118. * This can help preventing texture load conflict due to name collision.
  14119. */
  14120. Engine.prototype.clearInternalTexturesCache = function () {
  14121. this._internalTexturesCache = [];
  14122. };
  14123. /**
  14124. * Force the entire cache to be cleared
  14125. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14126. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14127. */
  14128. Engine.prototype.wipeCaches = function (bruteForce) {
  14129. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14130. return;
  14131. }
  14132. this._currentEffect = null;
  14133. this._unpackFlipYCached = null;
  14134. this._viewportCached.x = 0;
  14135. this._viewportCached.y = 0;
  14136. this._viewportCached.z = 0;
  14137. this._viewportCached.w = 0;
  14138. if (bruteForce) {
  14139. this.resetTextureCache();
  14140. this._currentProgram = null;
  14141. this._stencilState.reset();
  14142. this._depthCullingState.reset();
  14143. this.setDepthFunctionToLessOrEqual();
  14144. this._alphaState.reset();
  14145. }
  14146. this._resetVertexBufferBinding();
  14147. this._cachedIndexBuffer = null;
  14148. this._cachedEffectForVertexBuffers = null;
  14149. this._unbindVertexArrayObject();
  14150. this.bindIndexBuffer(null);
  14151. };
  14152. /**
  14153. * Set the compressed texture format to use, based on the formats you have, and the formats
  14154. * supported by the hardware / browser.
  14155. *
  14156. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14157. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14158. * to API arguments needed to compressed textures. This puts the burden on the container
  14159. * generator to house the arcane code for determining these for current & future formats.
  14160. *
  14161. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14162. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14163. *
  14164. * Note: The result of this call is not taken into account when a texture is base64.
  14165. *
  14166. * @param formatsAvailable defines the list of those format families you have created
  14167. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14168. *
  14169. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14170. * @returns The extension selected.
  14171. */
  14172. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14173. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14174. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14175. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14176. return this._textureFormatInUse = this._texturesSupported[i];
  14177. }
  14178. }
  14179. }
  14180. // actively set format to nothing, to allow this to be called more than once
  14181. // and possibly fail the 2nd time
  14182. this._textureFormatInUse = null;
  14183. return null;
  14184. };
  14185. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14186. var gl = this._gl;
  14187. var magFilter = gl.NEAREST;
  14188. var minFilter = gl.NEAREST;
  14189. switch (samplingMode) {
  14190. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14191. magFilter = gl.LINEAR;
  14192. if (generateMipMaps) {
  14193. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14194. }
  14195. else {
  14196. minFilter = gl.LINEAR;
  14197. }
  14198. break;
  14199. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14200. magFilter = gl.LINEAR;
  14201. if (generateMipMaps) {
  14202. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14203. }
  14204. else {
  14205. minFilter = gl.LINEAR;
  14206. }
  14207. break;
  14208. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14209. magFilter = gl.NEAREST;
  14210. if (generateMipMaps) {
  14211. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14212. }
  14213. else {
  14214. minFilter = gl.NEAREST;
  14215. }
  14216. break;
  14217. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14218. magFilter = gl.NEAREST;
  14219. if (generateMipMaps) {
  14220. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14221. }
  14222. else {
  14223. minFilter = gl.NEAREST;
  14224. }
  14225. break;
  14226. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14227. magFilter = gl.NEAREST;
  14228. if (generateMipMaps) {
  14229. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14230. }
  14231. else {
  14232. minFilter = gl.LINEAR;
  14233. }
  14234. break;
  14235. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14236. magFilter = gl.NEAREST;
  14237. if (generateMipMaps) {
  14238. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14239. }
  14240. else {
  14241. minFilter = gl.LINEAR;
  14242. }
  14243. break;
  14244. case Engine.TEXTURE_NEAREST_LINEAR:
  14245. magFilter = gl.NEAREST;
  14246. minFilter = gl.LINEAR;
  14247. break;
  14248. case Engine.TEXTURE_NEAREST_NEAREST:
  14249. magFilter = gl.NEAREST;
  14250. minFilter = gl.NEAREST;
  14251. break;
  14252. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14253. magFilter = gl.LINEAR;
  14254. if (generateMipMaps) {
  14255. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14256. }
  14257. else {
  14258. minFilter = gl.NEAREST;
  14259. }
  14260. break;
  14261. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14262. magFilter = gl.LINEAR;
  14263. if (generateMipMaps) {
  14264. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14265. }
  14266. else {
  14267. minFilter = gl.NEAREST;
  14268. }
  14269. break;
  14270. case Engine.TEXTURE_LINEAR_LINEAR:
  14271. magFilter = gl.LINEAR;
  14272. minFilter = gl.LINEAR;
  14273. break;
  14274. case Engine.TEXTURE_LINEAR_NEAREST:
  14275. magFilter = gl.LINEAR;
  14276. minFilter = gl.NEAREST;
  14277. break;
  14278. }
  14279. return {
  14280. min: minFilter,
  14281. mag: magFilter
  14282. };
  14283. };
  14284. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14285. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14286. var img;
  14287. var onload = function () {
  14288. loadedImages[index] = img;
  14289. loadedImages._internalCount++;
  14290. if (scene) {
  14291. scene._removePendingData(img);
  14292. }
  14293. if (loadedImages._internalCount === 6) {
  14294. onfinish(loadedImages);
  14295. }
  14296. };
  14297. var onerror = function (message, exception) {
  14298. if (scene) {
  14299. scene._removePendingData(img);
  14300. }
  14301. if (onErrorCallBack) {
  14302. onErrorCallBack(message, exception);
  14303. }
  14304. };
  14305. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14306. if (scene) {
  14307. scene._addPendingData(img);
  14308. }
  14309. };
  14310. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14311. if (onError === void 0) { onError = null; }
  14312. var loadedImages = [];
  14313. loadedImages._internalCount = 0;
  14314. for (var index = 0; index < 6; index++) {
  14315. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14316. }
  14317. };
  14318. ;
  14319. /** @hidden */
  14320. Engine.prototype._createTexture = function () {
  14321. var texture = this._gl.createTexture();
  14322. if (!texture) {
  14323. throw new Error("Unable to create texture");
  14324. }
  14325. return texture;
  14326. };
  14327. /**
  14328. * Usually called from BABYLON.Texture.ts.
  14329. * Passed information to create a WebGLTexture
  14330. * @param urlArg defines a value which contains one of the following:
  14331. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14332. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14333. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14334. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14335. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14336. * @param scene needed for loading to the correct scene
  14337. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14338. * @param onLoad optional callback to be called upon successful completion
  14339. * @param onError optional callback to be called upon failure
  14340. * @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
  14341. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14342. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14343. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14344. */
  14345. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14346. var _this = this;
  14347. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14348. if (onLoad === void 0) { onLoad = null; }
  14349. if (onError === void 0) { onError = null; }
  14350. if (buffer === void 0) { buffer = null; }
  14351. if (fallback === void 0) { fallback = null; }
  14352. if (format === void 0) { format = null; }
  14353. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14354. var fromData = url.substr(0, 5) === "data:";
  14355. var fromBlob = url.substr(0, 5) === "blob:";
  14356. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14357. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14358. // establish the file extension, if possible
  14359. var lastDot = url.lastIndexOf('.');
  14360. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14361. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14362. var isTGA = (extension.indexOf(".tga") === 0);
  14363. // determine if a ktx file should be substituted
  14364. var isKTX = false;
  14365. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14366. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14367. isKTX = true;
  14368. }
  14369. if (scene) {
  14370. scene._addPendingData(texture);
  14371. }
  14372. texture.url = url;
  14373. texture.generateMipMaps = !noMipmap;
  14374. texture.samplingMode = samplingMode;
  14375. texture.invertY = invertY;
  14376. if (!this._doNotHandleContextLost) {
  14377. // Keep a link to the buffer only if we plan to handle context lost
  14378. texture._buffer = buffer;
  14379. }
  14380. var onLoadObserver = null;
  14381. if (onLoad && !fallback) {
  14382. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14383. }
  14384. if (!fallback)
  14385. this._internalTexturesCache.push(texture);
  14386. var onerror = function (message, exception) {
  14387. if (scene) {
  14388. scene._removePendingData(texture);
  14389. }
  14390. if (onLoadObserver && !isKTX) {
  14391. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14392. texture.onLoadedObservable.remove(onLoadObserver);
  14393. }
  14394. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14395. if (isKTX) {
  14396. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14397. }
  14398. else if (BABYLON.Tools.UseFallbackTexture) {
  14399. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14400. }
  14401. if (onError) {
  14402. onError(message || "Unknown error", exception);
  14403. }
  14404. };
  14405. var callback = null;
  14406. // processing for non-image formats
  14407. if (isKTX || isTGA || isDDS) {
  14408. if (isKTX) {
  14409. callback = function (data) {
  14410. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14411. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14412. ktx.uploadLevels(texture, !noMipmap);
  14413. return false;
  14414. }, samplingMode);
  14415. };
  14416. }
  14417. else if (isTGA) {
  14418. callback = function (arrayBuffer) {
  14419. var data = new Uint8Array(arrayBuffer);
  14420. var header = BABYLON.TGATools.GetTGAHeader(data);
  14421. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14422. BABYLON.TGATools.UploadContent(texture, data);
  14423. return false;
  14424. }, samplingMode);
  14425. };
  14426. }
  14427. else if (isDDS) {
  14428. callback = function (data) {
  14429. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14430. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14431. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14432. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 1);
  14433. return false;
  14434. }, samplingMode);
  14435. };
  14436. }
  14437. if (!buffer) {
  14438. this._loadFile(url, function (data) {
  14439. if (callback) {
  14440. callback(data);
  14441. }
  14442. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14443. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14444. });
  14445. }
  14446. else {
  14447. if (callback) {
  14448. callback(buffer);
  14449. }
  14450. }
  14451. // image format processing
  14452. }
  14453. else {
  14454. var onload = function (img) {
  14455. if (fromBlob && !_this._doNotHandleContextLost) {
  14456. // We need to store the image if we need to rebuild the texture
  14457. // in case of a webgl context lost
  14458. texture._buffer = img;
  14459. }
  14460. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14461. var gl = _this._gl;
  14462. var isPot = (img.width === potWidth && img.height === potHeight);
  14463. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14464. if (isPot) {
  14465. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14466. return false;
  14467. }
  14468. var maxTextureSize = _this._caps.maxTextureSize;
  14469. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14470. _this._prepareWorkingCanvas();
  14471. if (!_this._workingCanvas || !_this._workingContext) {
  14472. return false;
  14473. }
  14474. _this._workingCanvas.width = potWidth;
  14475. _this._workingCanvas.height = potHeight;
  14476. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14477. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14478. texture.width = potWidth;
  14479. texture.height = potHeight;
  14480. return false;
  14481. }
  14482. else {
  14483. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14484. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14485. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14486. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14487. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14488. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14490. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14491. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14492. _this._releaseTexture(source_1);
  14493. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14494. continuationCallback();
  14495. });
  14496. }
  14497. return true;
  14498. }, samplingMode);
  14499. };
  14500. if (!fromData || isBase64) {
  14501. if (buffer instanceof HTMLImageElement) {
  14502. onload(buffer);
  14503. }
  14504. else {
  14505. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14506. }
  14507. }
  14508. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14509. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14510. }
  14511. else {
  14512. onload(buffer);
  14513. }
  14514. }
  14515. return texture;
  14516. };
  14517. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14518. var _this = this;
  14519. var rtt = this.createRenderTargetTexture({
  14520. width: destination.width,
  14521. height: destination.height,
  14522. }, {
  14523. generateMipMaps: false,
  14524. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14525. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14526. generateDepthBuffer: false,
  14527. generateStencilBuffer: false
  14528. });
  14529. if (!this._rescalePostProcess) {
  14530. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14531. }
  14532. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14533. _this._rescalePostProcess.onApply = function (effect) {
  14534. effect._bindTexture("textureSampler", source);
  14535. };
  14536. var hostingScene = scene;
  14537. if (!hostingScene) {
  14538. hostingScene = _this.scenes[_this.scenes.length - 1];
  14539. }
  14540. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14541. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14542. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14543. _this.unBindFramebuffer(rtt);
  14544. _this._releaseTexture(rtt);
  14545. if (onComplete) {
  14546. onComplete();
  14547. }
  14548. });
  14549. };
  14550. /**
  14551. * Update a raw texture
  14552. * @param texture defines the texture to update
  14553. * @param data defines the data to store in the texture
  14554. * @param format defines the format of the data
  14555. * @param invertY defines if data must be stored with Y axis inverted
  14556. * @param compression defines the compression used (null by default)
  14557. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14558. */
  14559. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14560. if (compression === void 0) { compression = null; }
  14561. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14562. if (!texture) {
  14563. return;
  14564. }
  14565. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14566. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14567. // babylon's internalFormat but gl's texImage2D format
  14568. var internalFormat = this._getInternalFormat(format);
  14569. var textureType = this._getWebGLTextureType(type);
  14570. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14571. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14572. if (!this._doNotHandleContextLost) {
  14573. texture._bufferView = data;
  14574. texture.format = format;
  14575. texture.type = type;
  14576. texture.invertY = invertY;
  14577. texture._compression = compression;
  14578. }
  14579. if (texture.width % 4 !== 0) {
  14580. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14581. }
  14582. if (compression && data) {
  14583. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14584. }
  14585. else {
  14586. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14587. }
  14588. if (texture.generateMipMaps) {
  14589. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14590. }
  14591. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14592. // this.resetTextureCache();
  14593. texture.isReady = true;
  14594. };
  14595. /**
  14596. * Creates a raw texture
  14597. * @param data defines the data to store in the texture
  14598. * @param width defines the width of the texture
  14599. * @param height defines the height of the texture
  14600. * @param format defines the format of the data
  14601. * @param generateMipMaps defines if the engine should generate the mip levels
  14602. * @param invertY defines if data must be stored with Y axis inverted
  14603. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14604. * @param compression defines the compression used (null by default)
  14605. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14606. * @returns the raw texture inside an InternalTexture
  14607. */
  14608. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14609. if (compression === void 0) { compression = null; }
  14610. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14611. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14612. texture.baseWidth = width;
  14613. texture.baseHeight = height;
  14614. texture.width = width;
  14615. texture.height = height;
  14616. texture.format = format;
  14617. texture.generateMipMaps = generateMipMaps;
  14618. texture.samplingMode = samplingMode;
  14619. texture.invertY = invertY;
  14620. texture._compression = compression;
  14621. texture.type = type;
  14622. if (!this._doNotHandleContextLost) {
  14623. texture._bufferView = data;
  14624. }
  14625. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14626. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14627. // Filters
  14628. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14630. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14631. if (generateMipMaps) {
  14632. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14633. }
  14634. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14635. this._internalTexturesCache.push(texture);
  14636. return texture;
  14637. };
  14638. /** @hidden */
  14639. Engine.prototype._unpackFlipY = function (value) {
  14640. if (this._unpackFlipYCached !== value) {
  14641. this._unpackFlipYCached = value;
  14642. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14643. }
  14644. };
  14645. /** @hidden */
  14646. Engine.prototype._getUnpackAlignement = function () {
  14647. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14648. };
  14649. /**
  14650. * Creates a dynamic texture
  14651. * @param width defines the width of the texture
  14652. * @param height defines the height of the texture
  14653. * @param generateMipMaps defines if the engine should generate the mip levels
  14654. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14655. * @returns the dynamic texture inside an InternalTexture
  14656. */
  14657. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14658. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14659. texture.baseWidth = width;
  14660. texture.baseHeight = height;
  14661. if (generateMipMaps) {
  14662. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14663. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14664. }
  14665. // this.resetTextureCache();
  14666. texture.width = width;
  14667. texture.height = height;
  14668. texture.isReady = false;
  14669. texture.generateMipMaps = generateMipMaps;
  14670. texture.samplingMode = samplingMode;
  14671. this.updateTextureSamplingMode(samplingMode, texture);
  14672. this._internalTexturesCache.push(texture);
  14673. return texture;
  14674. };
  14675. /**
  14676. * Update the sampling mode of a given texture
  14677. * @param samplingMode defines the required sampling mode
  14678. * @param texture defines the texture to update
  14679. */
  14680. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14681. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14682. if (texture.isCube) {
  14683. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14684. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14685. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14686. }
  14687. else if (texture.is3D) {
  14688. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14689. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14690. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14691. }
  14692. else {
  14693. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14694. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14695. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14696. }
  14697. texture.samplingMode = samplingMode;
  14698. };
  14699. /**
  14700. * Update the content of a dynamic texture
  14701. * @param texture defines the texture to update
  14702. * @param canvas defines the canvas containing the source
  14703. * @param invertY defines if data must be stored with Y axis inverted
  14704. * @param premulAlpha defines if alpha is stored as premultiplied
  14705. * @param format defines the format of the data
  14706. */
  14707. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14708. if (premulAlpha === void 0) { premulAlpha = false; }
  14709. if (!texture) {
  14710. return;
  14711. }
  14712. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14713. this._unpackFlipY(invertY);
  14714. if (premulAlpha) {
  14715. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14716. }
  14717. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14718. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14719. if (texture.generateMipMaps) {
  14720. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14721. }
  14722. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14723. if (premulAlpha) {
  14724. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14725. }
  14726. texture.isReady = true;
  14727. };
  14728. /**
  14729. * Update a video texture
  14730. * @param texture defines the texture to update
  14731. * @param video defines the video element to use
  14732. * @param invertY defines if data must be stored with Y axis inverted
  14733. */
  14734. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14735. if (!texture || texture._isDisabled) {
  14736. return;
  14737. }
  14738. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14739. this._unpackFlipY(!invertY); // Video are upside down by default
  14740. try {
  14741. // Testing video texture support
  14742. if (this._videoTextureSupported === undefined) {
  14743. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14744. if (this._gl.getError() !== 0) {
  14745. this._videoTextureSupported = false;
  14746. }
  14747. else {
  14748. this._videoTextureSupported = true;
  14749. }
  14750. }
  14751. // Copy video through the current working canvas if video texture is not supported
  14752. if (!this._videoTextureSupported) {
  14753. if (!texture._workingCanvas) {
  14754. texture._workingCanvas = document.createElement("canvas");
  14755. var context = texture._workingCanvas.getContext("2d");
  14756. if (!context) {
  14757. throw new Error("Unable to get 2d context");
  14758. }
  14759. texture._workingContext = context;
  14760. texture._workingCanvas.width = texture.width;
  14761. texture._workingCanvas.height = texture.height;
  14762. }
  14763. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14764. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14765. }
  14766. else {
  14767. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14768. }
  14769. if (texture.generateMipMaps) {
  14770. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14771. }
  14772. if (!wasPreviouslyBound) {
  14773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14774. }
  14775. // this.resetTextureCache();
  14776. texture.isReady = true;
  14777. }
  14778. catch (ex) {
  14779. // Something unexpected
  14780. // Let's disable the texture
  14781. texture._isDisabled = true;
  14782. }
  14783. };
  14784. /**
  14785. * Updates a depth texture Comparison Mode and Function.
  14786. * If the comparison Function is equal to 0, the mode will be set to none.
  14787. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14788. * @param texture The texture to set the comparison function for
  14789. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14790. */
  14791. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14792. if (this.webGLVersion === 1) {
  14793. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14794. return;
  14795. }
  14796. var gl = this._gl;
  14797. if (texture.isCube) {
  14798. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14799. if (comparisonFunction === 0) {
  14800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14802. }
  14803. else {
  14804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14806. }
  14807. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14808. }
  14809. else {
  14810. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14811. if (comparisonFunction === 0) {
  14812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14814. }
  14815. else {
  14816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14818. }
  14819. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14820. }
  14821. texture._comparisonFunction = comparisonFunction;
  14822. };
  14823. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14824. var width = size.width || size;
  14825. var height = size.height || size;
  14826. internalTexture.baseWidth = width;
  14827. internalTexture.baseHeight = height;
  14828. internalTexture.width = width;
  14829. internalTexture.height = height;
  14830. internalTexture.isReady = true;
  14831. internalTexture.samples = 1;
  14832. internalTexture.generateMipMaps = false;
  14833. internalTexture._generateDepthBuffer = true;
  14834. internalTexture._generateStencilBuffer = generateStencil;
  14835. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14836. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14837. internalTexture._comparisonFunction = comparisonFunction;
  14838. var gl = this._gl;
  14839. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14840. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14841. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14842. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14843. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14844. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14845. if (comparisonFunction === 0) {
  14846. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14847. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14848. }
  14849. else {
  14850. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14851. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14852. }
  14853. };
  14854. /**
  14855. * Creates a depth stencil texture.
  14856. * This is only available in WebGL 2 or with the depth texture extension available.
  14857. * @param size The size of face edge in the texture.
  14858. * @param options The options defining the texture.
  14859. * @returns The texture
  14860. */
  14861. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14862. if (options.isCube) {
  14863. var width = size.width || size;
  14864. return this._createDepthStencilCubeTexture(width, options);
  14865. }
  14866. else {
  14867. return this._createDepthStencilTexture(size, options);
  14868. }
  14869. };
  14870. /**
  14871. * Creates a depth stencil texture.
  14872. * This is only available in WebGL 2 or with the depth texture extension available.
  14873. * @param size The size of face edge in the texture.
  14874. * @param options The options defining the texture.
  14875. * @returns The texture
  14876. */
  14877. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14878. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14879. if (!this._caps.depthTextureExtension) {
  14880. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14881. return internalTexture;
  14882. }
  14883. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14884. var gl = this._gl;
  14885. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14886. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14887. if (this.webGLVersion > 1) {
  14888. if (internalOptions.generateStencil) {
  14889. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14890. }
  14891. else {
  14892. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14893. }
  14894. }
  14895. else {
  14896. if (internalOptions.generateStencil) {
  14897. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14898. }
  14899. else {
  14900. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14901. }
  14902. }
  14903. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14904. return internalTexture;
  14905. };
  14906. /**
  14907. * Creates a depth stencil cube texture.
  14908. * This is only available in WebGL 2.
  14909. * @param size The size of face edge in the cube texture.
  14910. * @param options The options defining the cube texture.
  14911. * @returns The cube texture
  14912. */
  14913. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14914. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14915. internalTexture.isCube = true;
  14916. if (this.webGLVersion === 1) {
  14917. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14918. return internalTexture;
  14919. }
  14920. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14921. var gl = this._gl;
  14922. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14923. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14924. // Create the depth/stencil buffer
  14925. for (var face = 0; face < 6; face++) {
  14926. if (internalOptions.generateStencil) {
  14927. 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);
  14928. }
  14929. else {
  14930. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14931. }
  14932. }
  14933. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14934. return internalTexture;
  14935. };
  14936. /**
  14937. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14938. * @param renderTarget The render target to set the frame buffer for
  14939. */
  14940. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14941. // Create the framebuffer
  14942. var internalTexture = renderTarget.getInternalTexture();
  14943. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14944. return;
  14945. }
  14946. var gl = this._gl;
  14947. var depthStencilTexture = renderTarget.depthStencilTexture;
  14948. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14949. if (depthStencilTexture.isCube) {
  14950. if (depthStencilTexture._generateStencilBuffer) {
  14951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14952. }
  14953. else {
  14954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14955. }
  14956. }
  14957. else {
  14958. if (depthStencilTexture._generateStencilBuffer) {
  14959. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14960. }
  14961. else {
  14962. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14963. }
  14964. }
  14965. this.bindUnboundFramebuffer(null);
  14966. };
  14967. /**
  14968. * Creates a new render target texture
  14969. * @param size defines the size of the texture
  14970. * @param options defines the options used to create the texture
  14971. * @returns a new render target texture stored in an InternalTexture
  14972. */
  14973. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14974. var fullOptions = new RenderTargetCreationOptions();
  14975. if (options !== undefined && typeof options === "object") {
  14976. fullOptions.generateMipMaps = options.generateMipMaps;
  14977. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14978. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14979. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14980. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14981. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14982. }
  14983. else {
  14984. fullOptions.generateMipMaps = options;
  14985. fullOptions.generateDepthBuffer = true;
  14986. fullOptions.generateStencilBuffer = false;
  14987. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14988. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  14989. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14990. }
  14991. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14992. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14993. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14994. }
  14995. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14996. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14997. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14998. }
  14999. var gl = this._gl;
  15000. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15001. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15002. var width = size.width || size;
  15003. var height = size.height || size;
  15004. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15005. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15006. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15007. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15008. }
  15009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15013. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15014. // Create the framebuffer
  15015. var currentFrameBuffer = this._currentFramebuffer;
  15016. var framebuffer = gl.createFramebuffer();
  15017. this.bindUnboundFramebuffer(framebuffer);
  15018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15019. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15020. if (fullOptions.generateMipMaps) {
  15021. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15022. }
  15023. // Unbind
  15024. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15025. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15026. this.bindUnboundFramebuffer(currentFrameBuffer);
  15027. texture._framebuffer = framebuffer;
  15028. texture.baseWidth = width;
  15029. texture.baseHeight = height;
  15030. texture.width = width;
  15031. texture.height = height;
  15032. texture.isReady = true;
  15033. texture.samples = 1;
  15034. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15035. texture.samplingMode = fullOptions.samplingMode;
  15036. texture.type = fullOptions.type;
  15037. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15038. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15039. // this.resetTextureCache();
  15040. this._internalTexturesCache.push(texture);
  15041. return texture;
  15042. };
  15043. /**
  15044. * Create a multi render target texture
  15045. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15046. * @param size defines the size of the texture
  15047. * @param options defines the creation options
  15048. * @returns the cube texture as an InternalTexture
  15049. */
  15050. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15051. var generateMipMaps = false;
  15052. var generateDepthBuffer = true;
  15053. var generateStencilBuffer = false;
  15054. var generateDepthTexture = false;
  15055. var textureCount = 1;
  15056. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15057. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15058. var types = new Array();
  15059. var samplingModes = new Array();
  15060. if (options !== undefined) {
  15061. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15062. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15063. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15064. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15065. textureCount = options.textureCount || 1;
  15066. if (options.types) {
  15067. types = options.types;
  15068. }
  15069. if (options.samplingModes) {
  15070. samplingModes = options.samplingModes;
  15071. }
  15072. }
  15073. var gl = this._gl;
  15074. // Create the framebuffer
  15075. var framebuffer = gl.createFramebuffer();
  15076. this.bindUnboundFramebuffer(framebuffer);
  15077. var width = size.width || size;
  15078. var height = size.height || size;
  15079. var textures = [];
  15080. var attachments = [];
  15081. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15082. for (var i = 0; i < textureCount; i++) {
  15083. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15084. var type = types[i] || defaultType;
  15085. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15086. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15087. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15088. }
  15089. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15090. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15091. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15092. }
  15093. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15094. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15095. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15096. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15097. }
  15098. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15099. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15100. textures.push(texture);
  15101. attachments.push(attachment);
  15102. gl.activeTexture(gl["TEXTURE" + i]);
  15103. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15108. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15109. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15110. if (generateMipMaps) {
  15111. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15112. }
  15113. // Unbind
  15114. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15115. texture._framebuffer = framebuffer;
  15116. texture._depthStencilBuffer = depthStencilBuffer;
  15117. texture.baseWidth = width;
  15118. texture.baseHeight = height;
  15119. texture.width = width;
  15120. texture.height = height;
  15121. texture.isReady = true;
  15122. texture.samples = 1;
  15123. texture.generateMipMaps = generateMipMaps;
  15124. texture.samplingMode = samplingMode;
  15125. texture.type = type;
  15126. texture._generateDepthBuffer = generateDepthBuffer;
  15127. texture._generateStencilBuffer = generateStencilBuffer;
  15128. texture._attachments = attachments;
  15129. this._internalTexturesCache.push(texture);
  15130. }
  15131. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15132. // Depth texture
  15133. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15134. gl.activeTexture(gl.TEXTURE0);
  15135. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15138. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15139. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15140. 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);
  15141. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15142. depthTexture._framebuffer = framebuffer;
  15143. depthTexture.baseWidth = width;
  15144. depthTexture.baseHeight = height;
  15145. depthTexture.width = width;
  15146. depthTexture.height = height;
  15147. depthTexture.isReady = true;
  15148. depthTexture.samples = 1;
  15149. depthTexture.generateMipMaps = generateMipMaps;
  15150. depthTexture.samplingMode = gl.NEAREST;
  15151. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15152. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15153. textures.push(depthTexture);
  15154. this._internalTexturesCache.push(depthTexture);
  15155. }
  15156. gl.drawBuffers(attachments);
  15157. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15158. this.bindUnboundFramebuffer(null);
  15159. this.resetTextureCache();
  15160. return textures;
  15161. };
  15162. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15163. if (samples === void 0) { samples = 1; }
  15164. var depthStencilBuffer = null;
  15165. var gl = this._gl;
  15166. // Create the depth/stencil buffer
  15167. if (generateStencilBuffer) {
  15168. depthStencilBuffer = gl.createRenderbuffer();
  15169. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15170. if (samples > 1) {
  15171. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15172. }
  15173. else {
  15174. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15175. }
  15176. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15177. }
  15178. else if (generateDepthBuffer) {
  15179. depthStencilBuffer = gl.createRenderbuffer();
  15180. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15181. if (samples > 1) {
  15182. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15183. }
  15184. else {
  15185. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15186. }
  15187. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15188. }
  15189. return depthStencilBuffer;
  15190. };
  15191. /**
  15192. * Updates the sample count of a render target texture
  15193. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15194. * @param texture defines the texture to update
  15195. * @param samples defines the sample count to set
  15196. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15197. */
  15198. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15199. if (this.webGLVersion < 2 || !texture) {
  15200. return 1;
  15201. }
  15202. if (texture.samples === samples) {
  15203. return samples;
  15204. }
  15205. var gl = this._gl;
  15206. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15207. // Dispose previous render buffers
  15208. if (texture._depthStencilBuffer) {
  15209. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15210. texture._depthStencilBuffer = null;
  15211. }
  15212. if (texture._MSAAFramebuffer) {
  15213. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15214. texture._MSAAFramebuffer = null;
  15215. }
  15216. if (texture._MSAARenderBuffer) {
  15217. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15218. texture._MSAARenderBuffer = null;
  15219. }
  15220. if (samples > 1) {
  15221. var framebuffer = gl.createFramebuffer();
  15222. if (!framebuffer) {
  15223. throw new Error("Unable to create multi sampled framebuffer");
  15224. }
  15225. texture._MSAAFramebuffer = framebuffer;
  15226. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15227. var colorRenderbuffer = gl.createRenderbuffer();
  15228. if (!colorRenderbuffer) {
  15229. throw new Error("Unable to create multi sampled framebuffer");
  15230. }
  15231. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15232. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15233. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15234. texture._MSAARenderBuffer = colorRenderbuffer;
  15235. }
  15236. else {
  15237. this.bindUnboundFramebuffer(texture._framebuffer);
  15238. }
  15239. texture.samples = samples;
  15240. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15241. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15242. this.bindUnboundFramebuffer(null);
  15243. return samples;
  15244. };
  15245. /**
  15246. * Update the sample count for a given multiple render target texture
  15247. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15248. * @param textures defines the textures to update
  15249. * @param samples defines the sample count to set
  15250. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15251. */
  15252. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15253. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15254. return 1;
  15255. }
  15256. if (textures[0].samples === samples) {
  15257. return samples;
  15258. }
  15259. var gl = this._gl;
  15260. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15261. // Dispose previous render buffers
  15262. if (textures[0]._depthStencilBuffer) {
  15263. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15264. textures[0]._depthStencilBuffer = null;
  15265. }
  15266. if (textures[0]._MSAAFramebuffer) {
  15267. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15268. textures[0]._MSAAFramebuffer = null;
  15269. }
  15270. for (var i = 0; i < textures.length; i++) {
  15271. if (textures[i]._MSAARenderBuffer) {
  15272. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15273. textures[i]._MSAARenderBuffer = null;
  15274. }
  15275. }
  15276. if (samples > 1) {
  15277. var framebuffer = gl.createFramebuffer();
  15278. if (!framebuffer) {
  15279. throw new Error("Unable to create multi sampled framebuffer");
  15280. }
  15281. this.bindUnboundFramebuffer(framebuffer);
  15282. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15283. var attachments = [];
  15284. for (var i = 0; i < textures.length; i++) {
  15285. var texture = textures[i];
  15286. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15287. var colorRenderbuffer = gl.createRenderbuffer();
  15288. if (!colorRenderbuffer) {
  15289. throw new Error("Unable to create multi sampled framebuffer");
  15290. }
  15291. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15292. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15293. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15294. texture._MSAAFramebuffer = framebuffer;
  15295. texture._MSAARenderBuffer = colorRenderbuffer;
  15296. texture.samples = samples;
  15297. texture._depthStencilBuffer = depthStencilBuffer;
  15298. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15299. attachments.push(attachment);
  15300. }
  15301. gl.drawBuffers(attachments);
  15302. }
  15303. else {
  15304. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15305. }
  15306. this.bindUnboundFramebuffer(null);
  15307. return samples;
  15308. };
  15309. /** @hidden */
  15310. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15311. if (faceIndex === void 0) { faceIndex = 0; }
  15312. if (lod === void 0) { lod = 0; }
  15313. var gl = this._gl;
  15314. var target = gl.TEXTURE_2D;
  15315. if (texture.isCube) {
  15316. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15317. }
  15318. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15319. };
  15320. /** @hidden */
  15321. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15322. if (faceIndex === void 0) { faceIndex = 0; }
  15323. if (lod === void 0) { lod = 0; }
  15324. var gl = this._gl;
  15325. var textureType = this._getWebGLTextureType(texture.type);
  15326. var format = this._getInternalFormat(texture.format);
  15327. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15328. this._unpackFlipY(texture.invertY);
  15329. var target = gl.TEXTURE_2D;
  15330. if (texture.isCube) {
  15331. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15332. }
  15333. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15334. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15335. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15336. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15337. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15338. };
  15339. /** @hidden */
  15340. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15341. if (faceIndex === void 0) { faceIndex = 0; }
  15342. if (lod === void 0) { lod = 0; }
  15343. var gl = this._gl;
  15344. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15345. this._bindTextureDirectly(bindTarget, texture, true);
  15346. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15347. this._bindTextureDirectly(bindTarget, null, true);
  15348. };
  15349. /** @hidden */
  15350. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15351. if (faceIndex === void 0) { faceIndex = 0; }
  15352. if (lod === void 0) { lod = 0; }
  15353. var gl = this._gl;
  15354. var textureType = this._getWebGLTextureType(texture.type);
  15355. var format = this._getInternalFormat(texture.format);
  15356. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15357. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15358. this._bindTextureDirectly(bindTarget, texture, true);
  15359. this._unpackFlipY(texture.invertY);
  15360. var target = gl.TEXTURE_2D;
  15361. if (texture.isCube) {
  15362. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15363. }
  15364. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15365. this._bindTextureDirectly(bindTarget, null, true);
  15366. };
  15367. /**
  15368. * Creates a new render target cube texture
  15369. * @param size defines the size of the texture
  15370. * @param options defines the options used to create the texture
  15371. * @returns a new render target cube texture stored in an InternalTexture
  15372. */
  15373. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15374. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15375. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15376. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15377. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15378. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15379. }
  15380. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15381. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15382. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15383. }
  15384. var gl = this._gl;
  15385. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15386. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15387. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15388. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15389. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15390. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15391. }
  15392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15394. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15396. for (var face = 0; face < 6; face++) {
  15397. 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);
  15398. }
  15399. // Create the framebuffer
  15400. var framebuffer = gl.createFramebuffer();
  15401. this.bindUnboundFramebuffer(framebuffer);
  15402. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15403. // MipMaps
  15404. if (fullOptions.generateMipMaps) {
  15405. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15406. }
  15407. // Unbind
  15408. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15409. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15410. this.bindUnboundFramebuffer(null);
  15411. texture._framebuffer = framebuffer;
  15412. texture.width = size;
  15413. texture.height = size;
  15414. texture.isReady = true;
  15415. texture.isCube = true;
  15416. texture.samples = 1;
  15417. texture.generateMipMaps = fullOptions.generateMipMaps;
  15418. texture.samplingMode = fullOptions.samplingMode;
  15419. texture.type = fullOptions.type;
  15420. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15421. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15422. this._internalTexturesCache.push(texture);
  15423. return texture;
  15424. };
  15425. /**
  15426. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15427. * @param rootUrl defines the url where the file to load is located
  15428. * @param scene defines the current scene
  15429. * @param lodScale defines scale to apply to the mip map selection
  15430. * @param lodOffset defines offset to apply to the mip map selection
  15431. * @param onLoad defines an optional callback raised when the texture is loaded
  15432. * @param onError defines an optional callback raised if there is an issue to load the texture
  15433. * @param format defines the format of the data
  15434. * @param forcedExtension defines the extension to use to pick the right loader
  15435. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15436. * @returns the cube texture as an InternalTexture
  15437. */
  15438. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15439. var _this = this;
  15440. if (onLoad === void 0) { onLoad = null; }
  15441. if (onError === void 0) { onError = null; }
  15442. if (forcedExtension === void 0) { forcedExtension = null; }
  15443. if (createPolynomials === void 0) { createPolynomials = true; }
  15444. var callback = function (loadData) {
  15445. if (!loadData) {
  15446. if (onLoad) {
  15447. onLoad(null);
  15448. }
  15449. return;
  15450. }
  15451. var texture = loadData.texture;
  15452. if (!createPolynomials) {
  15453. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15454. }
  15455. else if (loadData.info.sphericalPolynomial) {
  15456. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15457. }
  15458. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15459. if (_this._caps.textureLOD) {
  15460. // Do not add extra process if texture lod is supported.
  15461. if (onLoad) {
  15462. onLoad(texture);
  15463. }
  15464. return;
  15465. }
  15466. var mipSlices = 3;
  15467. var gl = _this._gl;
  15468. var width = loadData.width;
  15469. if (!width) {
  15470. return;
  15471. }
  15472. var textures = [];
  15473. for (var i = 0; i < mipSlices; i++) {
  15474. //compute LOD from even spacing in smoothness (matching shader calculation)
  15475. var smoothness = i / (mipSlices - 1);
  15476. var roughness = 1 - smoothness;
  15477. var minLODIndex = lodOffset; // roughness = 0
  15478. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15479. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15480. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15481. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15482. glTextureFromLod.isCube = true;
  15483. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15488. if (loadData.isDDS) {
  15489. var info = loadData.info;
  15490. var data = loadData.data;
  15491. _this._unpackFlipY(info.isCompressed);
  15492. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15493. }
  15494. else {
  15495. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15496. }
  15497. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15498. // Wrap in a base texture for easy binding.
  15499. var lodTexture = new BABYLON.BaseTexture(scene);
  15500. lodTexture.isCube = true;
  15501. lodTexture._texture = glTextureFromLod;
  15502. glTextureFromLod.isReady = true;
  15503. textures.push(lodTexture);
  15504. }
  15505. texture._lodTextureHigh = textures[2];
  15506. texture._lodTextureMid = textures[1];
  15507. texture._lodTextureLow = textures[0];
  15508. if (onLoad) {
  15509. onLoad(texture);
  15510. }
  15511. };
  15512. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15513. };
  15514. /**
  15515. * Creates a cube texture
  15516. * @param rootUrl defines the url where the files to load is located
  15517. * @param scene defines the current scene
  15518. * @param files defines the list of files to load (1 per face)
  15519. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15520. * @param onLoad defines an optional callback raised when the texture is loaded
  15521. * @param onError defines an optional callback raised if there is an issue to load the texture
  15522. * @param format defines the format of the data
  15523. * @param forcedExtension defines the extension to use to pick the right loader
  15524. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15525. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15526. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15527. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15528. * @returns the cube texture as an InternalTexture
  15529. */
  15530. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15531. var _this = this;
  15532. if (onLoad === void 0) { onLoad = null; }
  15533. if (onError === void 0) { onError = null; }
  15534. if (forcedExtension === void 0) { forcedExtension = null; }
  15535. if (createPolynomials === void 0) { createPolynomials = false; }
  15536. if (lodScale === void 0) { lodScale = 0; }
  15537. if (lodOffset === void 0) { lodOffset = 0; }
  15538. if (fallback === void 0) { fallback = null; }
  15539. var gl = this._gl;
  15540. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15541. texture.isCube = true;
  15542. texture.url = rootUrl;
  15543. texture.generateMipMaps = !noMipmap;
  15544. texture._lodGenerationScale = lodScale;
  15545. texture._lodGenerationOffset = lodOffset;
  15546. if (!this._doNotHandleContextLost) {
  15547. texture._extension = forcedExtension;
  15548. texture._files = files;
  15549. }
  15550. var isKTX = false;
  15551. var isDDS = false;
  15552. var isEnv = false;
  15553. var lastDot = rootUrl.lastIndexOf('.');
  15554. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15555. if (this._textureFormatInUse && !fallback) {
  15556. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15557. isKTX = true;
  15558. }
  15559. else {
  15560. isDDS = (extension === ".dds");
  15561. isEnv = (extension === ".env");
  15562. }
  15563. var onerror = function (request, exception) {
  15564. if (isKTX) {
  15565. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15566. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15567. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15568. }
  15569. if (onError && request) {
  15570. onError(request.status + " " + request.statusText, exception);
  15571. }
  15572. };
  15573. if (isKTX) {
  15574. this._loadFile(rootUrl, function (data) {
  15575. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15576. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15577. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15578. _this._unpackFlipY(true);
  15579. ktx.uploadLevels(texture, !noMipmap);
  15580. _this.setCubeMapTextureParams(gl, loadMipmap);
  15581. texture.width = ktx.pixelWidth;
  15582. texture.height = ktx.pixelHeight;
  15583. texture.isReady = true;
  15584. }, undefined, undefined, true, onerror);
  15585. }
  15586. else if (isEnv) {
  15587. this._loadFile(rootUrl, function (data) {
  15588. data = data;
  15589. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15590. if (info) {
  15591. texture.width = info.width;
  15592. texture.height = info.width;
  15593. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15594. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15595. texture.isReady = true;
  15596. if (onLoad) {
  15597. onLoad();
  15598. }
  15599. });
  15600. }
  15601. else if (onError) {
  15602. onError("Can not parse the environment file", null);
  15603. }
  15604. }, undefined, undefined, true, onerror);
  15605. }
  15606. else if (isDDS) {
  15607. if (files && files.length === 6) {
  15608. this._cascadeLoadFiles(scene, function (imgs) {
  15609. var info;
  15610. var loadMipmap = false;
  15611. var width = 0;
  15612. for (var index = 0; index < imgs.length; index++) {
  15613. var data = imgs[index];
  15614. info = BABYLON.DDSTools.GetDDSInfo(data);
  15615. texture.width = info.width;
  15616. texture.height = info.height;
  15617. width = info.width;
  15618. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15619. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15620. _this._unpackFlipY(info.isCompressed);
  15621. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6, -1, index);
  15622. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15623. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15624. }
  15625. }
  15626. _this.setCubeMapTextureParams(gl, loadMipmap);
  15627. texture.isReady = true;
  15628. if (onLoad) {
  15629. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15630. }
  15631. }, files, onError);
  15632. }
  15633. else {
  15634. this._loadFile(rootUrl, function (data) {
  15635. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15636. texture.width = info.width;
  15637. texture.height = info.height;
  15638. if (createPolynomials) {
  15639. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15640. }
  15641. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15642. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15643. _this._unpackFlipY(info.isCompressed);
  15644. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6);
  15645. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15646. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15647. }
  15648. _this.setCubeMapTextureParams(gl, loadMipmap);
  15649. texture.isReady = true;
  15650. if (onLoad) {
  15651. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15652. }
  15653. }, undefined, undefined, true, onerror);
  15654. }
  15655. }
  15656. else {
  15657. if (!files) {
  15658. throw new Error("Cannot load cubemap because files were not defined");
  15659. }
  15660. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15661. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15662. var height = width;
  15663. _this._prepareWorkingCanvas();
  15664. if (!_this._workingCanvas || !_this._workingContext) {
  15665. return;
  15666. }
  15667. _this._workingCanvas.width = width;
  15668. _this._workingCanvas.height = height;
  15669. var faces = [
  15670. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15671. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15672. ];
  15673. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15674. _this._unpackFlipY(false);
  15675. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15676. for (var index = 0; index < faces.length; index++) {
  15677. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15678. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15679. }
  15680. if (!noMipmap) {
  15681. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15682. }
  15683. _this.setCubeMapTextureParams(gl, !noMipmap);
  15684. texture.width = width;
  15685. texture.height = height;
  15686. texture.isReady = true;
  15687. if (format) {
  15688. texture.format = format;
  15689. }
  15690. texture.onLoadedObservable.notifyObservers(texture);
  15691. texture.onLoadedObservable.clear();
  15692. if (onLoad) {
  15693. onLoad();
  15694. }
  15695. }, files, onError);
  15696. }
  15697. this._internalTexturesCache.push(texture);
  15698. return texture;
  15699. };
  15700. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15705. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15706. // this.resetTextureCache();
  15707. };
  15708. /**
  15709. * Update a raw cube texture
  15710. * @param texture defines the texture to udpdate
  15711. * @param data defines the data to store
  15712. * @param format defines the data format
  15713. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15714. * @param invertY defines if data must be stored with Y axis inverted
  15715. * @param compression defines the compression used (null by default)
  15716. * @param level defines which level of the texture to update
  15717. */
  15718. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15719. if (compression === void 0) { compression = null; }
  15720. if (level === void 0) { level = 0; }
  15721. texture._bufferViewArray = data;
  15722. texture.format = format;
  15723. texture.type = type;
  15724. texture.invertY = invertY;
  15725. texture._compression = compression;
  15726. var gl = this._gl;
  15727. var textureType = this._getWebGLTextureType(type);
  15728. var internalFormat = this._getInternalFormat(format);
  15729. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15730. var needConversion = false;
  15731. if (internalFormat === gl.RGB) {
  15732. internalFormat = gl.RGBA;
  15733. needConversion = true;
  15734. }
  15735. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15736. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15737. if (texture.width % 4 !== 0) {
  15738. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15739. }
  15740. // Data are known to be in +X +Y +Z -X -Y -Z
  15741. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15742. var faceData = data[faceIndex];
  15743. if (compression) {
  15744. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15745. }
  15746. else {
  15747. if (needConversion) {
  15748. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15749. }
  15750. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15751. }
  15752. }
  15753. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15754. if (isPot && texture.generateMipMaps && level === 0) {
  15755. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15756. }
  15757. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15758. // this.resetTextureCache();
  15759. texture.isReady = true;
  15760. };
  15761. /**
  15762. * Creates a new raw cube texture
  15763. * @param data defines the array of data to use to create each face
  15764. * @param size defines the size of the textures
  15765. * @param format defines the format of the data
  15766. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15767. * @param generateMipMaps defines if the engine should generate the mip levels
  15768. * @param invertY defines if data must be stored with Y axis inverted
  15769. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15770. * @param compression defines the compression used (null by default)
  15771. * @returns the cube texture as an InternalTexture
  15772. */
  15773. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15774. if (compression === void 0) { compression = null; }
  15775. var gl = this._gl;
  15776. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15777. texture.isCube = true;
  15778. texture.generateMipMaps = generateMipMaps;
  15779. texture.format = format;
  15780. texture.type = type;
  15781. if (!this._doNotHandleContextLost) {
  15782. texture._bufferViewArray = data;
  15783. }
  15784. var textureType = this._getWebGLTextureType(type);
  15785. var internalFormat = this._getInternalFormat(format);
  15786. if (internalFormat === gl.RGB) {
  15787. internalFormat = gl.RGBA;
  15788. }
  15789. var width = size;
  15790. var height = width;
  15791. texture.width = width;
  15792. texture.height = height;
  15793. // Double check on POT to generate Mips.
  15794. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15795. if (!isPot) {
  15796. generateMipMaps = false;
  15797. }
  15798. // Upload data if needed. The texture won't be ready until then.
  15799. if (data) {
  15800. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15801. }
  15802. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15803. // Filters
  15804. if (data && generateMipMaps) {
  15805. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15806. }
  15807. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15809. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15810. }
  15811. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15812. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15814. }
  15815. else {
  15816. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15819. }
  15820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15822. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15823. return texture;
  15824. };
  15825. /**
  15826. * Creates a new raw cube texture from a specified url
  15827. * @param url defines the url where the data is located
  15828. * @param scene defines the current scene
  15829. * @param size defines the size of the textures
  15830. * @param format defines the format of the data
  15831. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15832. * @param noMipmap defines if the engine should avoid generating the mip levels
  15833. * @param callback defines a callback used to extract texture data from loaded data
  15834. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15835. * @param onLoad defines a callback called when texture is loaded
  15836. * @param onError defines a callback called if there is an error
  15837. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15838. * @param invertY defines if data must be stored with Y axis inverted
  15839. * @returns the cube texture as an InternalTexture
  15840. */
  15841. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15842. var _this = this;
  15843. if (onLoad === void 0) { onLoad = null; }
  15844. if (onError === void 0) { onError = null; }
  15845. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15846. if (invertY === void 0) { invertY = false; }
  15847. var gl = this._gl;
  15848. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15849. scene._addPendingData(texture);
  15850. texture.url = url;
  15851. this._internalTexturesCache.push(texture);
  15852. var onerror = function (request, exception) {
  15853. scene._removePendingData(texture);
  15854. if (onError && request) {
  15855. onError(request.status + " " + request.statusText, exception);
  15856. }
  15857. };
  15858. var internalCallback = function (data) {
  15859. var width = texture.width;
  15860. var faceDataArrays = callback(data);
  15861. if (!faceDataArrays) {
  15862. return;
  15863. }
  15864. if (mipmapGenerator) {
  15865. var textureType = _this._getWebGLTextureType(type);
  15866. var internalFormat = _this._getInternalFormat(format);
  15867. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15868. var needConversion = false;
  15869. if (internalFormat === gl.RGB) {
  15870. internalFormat = gl.RGBA;
  15871. needConversion = true;
  15872. }
  15873. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15874. _this._unpackFlipY(false);
  15875. var mipData = mipmapGenerator(faceDataArrays);
  15876. for (var level = 0; level < mipData.length; level++) {
  15877. var mipSize = width >> level;
  15878. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15879. var mipFaceData = mipData[level][faceIndex];
  15880. if (needConversion) {
  15881. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15882. }
  15883. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15884. }
  15885. }
  15886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15887. }
  15888. else {
  15889. texture.generateMipMaps = !noMipmap;
  15890. if (type === Engine.TEXTURETYPE_FLOAT && !_this._caps.textureFloatLinearFiltering) {
  15891. texture.generateMipMaps = false;
  15892. }
  15893. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15894. }
  15895. texture.isReady = true;
  15896. // this.resetTextureCache();
  15897. scene._removePendingData(texture);
  15898. if (onLoad) {
  15899. onLoad();
  15900. }
  15901. };
  15902. this._loadFile(url, function (data) {
  15903. internalCallback(data);
  15904. }, undefined, scene.database, true, onerror);
  15905. return texture;
  15906. };
  15907. ;
  15908. /**
  15909. * Update a raw 3D texture
  15910. * @param texture defines the texture to update
  15911. * @param data defines the data to store
  15912. * @param format defines the data format
  15913. * @param invertY defines if data must be stored with Y axis inverted
  15914. * @param compression defines the used compression (can be null)
  15915. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15916. */
  15917. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15918. if (compression === void 0) { compression = null; }
  15919. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15920. var internalType = this._getWebGLTextureType(textureType);
  15921. var internalFormat = this._getInternalFormat(format);
  15922. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15923. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15924. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15925. if (!this._doNotHandleContextLost) {
  15926. texture._bufferView = data;
  15927. texture.format = format;
  15928. texture.invertY = invertY;
  15929. texture._compression = compression;
  15930. }
  15931. if (texture.width % 4 !== 0) {
  15932. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15933. }
  15934. if (compression && data) {
  15935. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15936. }
  15937. else {
  15938. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15939. }
  15940. if (texture.generateMipMaps) {
  15941. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15942. }
  15943. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15944. // this.resetTextureCache();
  15945. texture.isReady = true;
  15946. };
  15947. /**
  15948. * Creates a new raw 3D texture
  15949. * @param data defines the data used to create the texture
  15950. * @param width defines the width of the texture
  15951. * @param height defines the height of the texture
  15952. * @param depth defines the depth of the texture
  15953. * @param format defines the format of the texture
  15954. * @param generateMipMaps defines if the engine must generate mip levels
  15955. * @param invertY defines if data must be stored with Y axis inverted
  15956. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15957. * @param compression defines the compressed used (can be null)
  15958. * @param textureType defines the compressed used (can be null)
  15959. * @returns a new raw 3D texture (stored in an InternalTexture)
  15960. */
  15961. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15962. if (compression === void 0) { compression = null; }
  15963. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15964. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15965. texture.baseWidth = width;
  15966. texture.baseHeight = height;
  15967. texture.baseDepth = depth;
  15968. texture.width = width;
  15969. texture.height = height;
  15970. texture.depth = depth;
  15971. texture.format = format;
  15972. texture.type = textureType;
  15973. texture.generateMipMaps = generateMipMaps;
  15974. texture.samplingMode = samplingMode;
  15975. texture.is3D = true;
  15976. if (!this._doNotHandleContextLost) {
  15977. texture._bufferView = data;
  15978. }
  15979. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15980. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15981. // Filters
  15982. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15983. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15984. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15985. if (generateMipMaps) {
  15986. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15987. }
  15988. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15989. this._internalTexturesCache.push(texture);
  15990. return texture;
  15991. };
  15992. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15993. var gl = this._gl;
  15994. if (!gl) {
  15995. return;
  15996. }
  15997. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16000. if (!noMipmap && !isCompressed) {
  16001. gl.generateMipmap(gl.TEXTURE_2D);
  16002. }
  16003. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16004. // this.resetTextureCache();
  16005. if (scene) {
  16006. scene._removePendingData(texture);
  16007. }
  16008. texture.onLoadedObservable.notifyObservers(texture);
  16009. texture.onLoadedObservable.clear();
  16010. };
  16011. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16012. var _this = this;
  16013. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16014. var maxTextureSize = this.getCaps().maxTextureSize;
  16015. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16016. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16017. var gl = this._gl;
  16018. if (!gl) {
  16019. return;
  16020. }
  16021. if (!texture._webGLTexture) {
  16022. // this.resetTextureCache();
  16023. if (scene) {
  16024. scene._removePendingData(texture);
  16025. }
  16026. return;
  16027. }
  16028. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16029. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16030. texture.baseWidth = width;
  16031. texture.baseHeight = height;
  16032. texture.width = potWidth;
  16033. texture.height = potHeight;
  16034. texture.isReady = true;
  16035. if (processFunction(potWidth, potHeight, function () {
  16036. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16037. })) {
  16038. // Returning as texture needs extra async steps
  16039. return;
  16040. }
  16041. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16042. };
  16043. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16044. // Create new RGBA data container.
  16045. var rgbaData;
  16046. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16047. rgbaData = new Float32Array(width * height * 4);
  16048. }
  16049. else {
  16050. rgbaData = new Uint32Array(width * height * 4);
  16051. }
  16052. // Convert each pixel.
  16053. for (var x = 0; x < width; x++) {
  16054. for (var y = 0; y < height; y++) {
  16055. var index = (y * width + x) * 3;
  16056. var newIndex = (y * width + x) * 4;
  16057. // Map Old Value to new value.
  16058. rgbaData[newIndex + 0] = rgbData[index + 0];
  16059. rgbaData[newIndex + 1] = rgbData[index + 1];
  16060. rgbaData[newIndex + 2] = rgbData[index + 2];
  16061. // Add fully opaque alpha channel.
  16062. rgbaData[newIndex + 3] = 1;
  16063. }
  16064. }
  16065. return rgbaData;
  16066. };
  16067. /** @hidden */
  16068. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16069. var gl = this._gl;
  16070. if (texture._framebuffer) {
  16071. gl.deleteFramebuffer(texture._framebuffer);
  16072. texture._framebuffer = null;
  16073. }
  16074. if (texture._depthStencilBuffer) {
  16075. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16076. texture._depthStencilBuffer = null;
  16077. }
  16078. if (texture._MSAAFramebuffer) {
  16079. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16080. texture._MSAAFramebuffer = null;
  16081. }
  16082. if (texture._MSAARenderBuffer) {
  16083. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16084. texture._MSAARenderBuffer = null;
  16085. }
  16086. };
  16087. /** @hidden */
  16088. Engine.prototype._releaseTexture = function (texture) {
  16089. var gl = this._gl;
  16090. this._releaseFramebufferObjects(texture);
  16091. gl.deleteTexture(texture._webGLTexture);
  16092. // Unbind channels
  16093. this.unbindAllTextures();
  16094. var index = this._internalTexturesCache.indexOf(texture);
  16095. if (index !== -1) {
  16096. this._internalTexturesCache.splice(index, 1);
  16097. }
  16098. // Integrated fixed lod samplers.
  16099. if (texture._lodTextureHigh) {
  16100. texture._lodTextureHigh.dispose();
  16101. }
  16102. if (texture._lodTextureMid) {
  16103. texture._lodTextureMid.dispose();
  16104. }
  16105. if (texture._lodTextureLow) {
  16106. texture._lodTextureLow.dispose();
  16107. }
  16108. // Set output texture of post process to null if the texture has been released/disposed
  16109. this.scenes.forEach(function (scene) {
  16110. scene.postProcesses.forEach(function (postProcess) {
  16111. if (postProcess._outputTexture == texture) {
  16112. postProcess._outputTexture = null;
  16113. }
  16114. });
  16115. scene.cameras.forEach(function (camera) {
  16116. camera._postProcesses.forEach(function (postProcess) {
  16117. if (postProcess) {
  16118. if (postProcess._outputTexture == texture) {
  16119. postProcess._outputTexture = null;
  16120. }
  16121. }
  16122. });
  16123. });
  16124. });
  16125. };
  16126. Engine.prototype.setProgram = function (program) {
  16127. if (this._currentProgram !== program) {
  16128. this._gl.useProgram(program);
  16129. this._currentProgram = program;
  16130. }
  16131. };
  16132. /**
  16133. * Binds an effect to the webGL context
  16134. * @param effect defines the effect to bind
  16135. */
  16136. Engine.prototype.bindSamplers = function (effect) {
  16137. this.setProgram(effect.getProgram());
  16138. var samplers = effect.getSamplers();
  16139. for (var index = 0; index < samplers.length; index++) {
  16140. var uniform = effect.getUniform(samplers[index]);
  16141. if (uniform) {
  16142. this._boundUniforms[index] = uniform;
  16143. }
  16144. }
  16145. this._currentEffect = null;
  16146. };
  16147. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16148. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16149. return;
  16150. }
  16151. // Remove
  16152. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16153. // Bind last to it
  16154. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16155. // Bind to dummy
  16156. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16157. };
  16158. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16159. if (!internalTexture) {
  16160. return -1;
  16161. }
  16162. internalTexture._initialSlot = channel;
  16163. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16164. if (channel !== internalTexture._designatedSlot) {
  16165. this._textureCollisions.addCount(1, false);
  16166. }
  16167. }
  16168. else {
  16169. if (channel !== internalTexture._designatedSlot) {
  16170. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16171. return internalTexture._designatedSlot;
  16172. }
  16173. else {
  16174. // No slot for this texture, let's pick a new one (if we find a free slot)
  16175. if (this._nextFreeTextureSlots.length) {
  16176. return this._nextFreeTextureSlots[0];
  16177. }
  16178. // We need to recycle the oldest bound texture, sorry.
  16179. this._textureCollisions.addCount(1, false);
  16180. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16181. }
  16182. }
  16183. }
  16184. return channel;
  16185. };
  16186. Engine.prototype._linkTrackers = function (previous, next) {
  16187. previous.next = next;
  16188. next.previous = previous;
  16189. };
  16190. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16191. var currentSlot = internalTexture._designatedSlot;
  16192. if (currentSlot === -1) {
  16193. return -1;
  16194. }
  16195. internalTexture._designatedSlot = -1;
  16196. if (this.disableTextureBindingOptimization) {
  16197. return -1;
  16198. }
  16199. // Remove from bound list
  16200. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16201. // Free the slot
  16202. this._boundTexturesCache[currentSlot] = null;
  16203. this._nextFreeTextureSlots.push(currentSlot);
  16204. return currentSlot;
  16205. };
  16206. Engine.prototype._activateCurrentTexture = function () {
  16207. if (this._currentTextureChannel !== this._activeChannel) {
  16208. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16209. this._currentTextureChannel = this._activeChannel;
  16210. }
  16211. };
  16212. /** @hidden */
  16213. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16214. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16215. if (force === void 0) { force = false; }
  16216. var wasPreviouslyBound = false;
  16217. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16218. this._activeChannel = texture._designatedSlot;
  16219. }
  16220. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16221. var isTextureForRendering = texture && texture._initialSlot > -1;
  16222. if (currentTextureBound !== texture || force) {
  16223. if (currentTextureBound) {
  16224. this._removeDesignatedSlot(currentTextureBound);
  16225. }
  16226. this._activateCurrentTexture();
  16227. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16228. this._boundTexturesCache[this._activeChannel] = texture;
  16229. if (texture) {
  16230. if (!this.disableTextureBindingOptimization) {
  16231. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16232. if (slotIndex > -1) {
  16233. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16234. }
  16235. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16236. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16237. }
  16238. texture._designatedSlot = this._activeChannel;
  16239. }
  16240. }
  16241. else if (forTextureDataUpdate) {
  16242. wasPreviouslyBound = true;
  16243. this._activateCurrentTexture();
  16244. }
  16245. if (isTextureForRendering && !forTextureDataUpdate) {
  16246. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16247. }
  16248. return wasPreviouslyBound;
  16249. };
  16250. /** @hidden */
  16251. Engine.prototype._bindTexture = function (channel, texture) {
  16252. if (channel < 0) {
  16253. return;
  16254. }
  16255. if (texture) {
  16256. channel = this._getCorrectTextureChannel(channel, texture);
  16257. }
  16258. this._activeChannel = channel;
  16259. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16260. };
  16261. /**
  16262. * Sets a texture to the webGL context from a postprocess
  16263. * @param channel defines the channel to use
  16264. * @param postProcess defines the source postprocess
  16265. */
  16266. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16267. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16268. };
  16269. /**
  16270. * Binds the output of the passed in post process to the texture channel specified
  16271. * @param channel The channel the texture should be bound to
  16272. * @param postProcess The post process which's output should be bound
  16273. */
  16274. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16275. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16276. };
  16277. /**
  16278. * Unbind all textures from the webGL context
  16279. */
  16280. Engine.prototype.unbindAllTextures = function () {
  16281. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16282. this._activeChannel = channel;
  16283. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16284. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16285. if (this.webGLVersion > 1) {
  16286. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16287. }
  16288. }
  16289. };
  16290. /**
  16291. * Sets a texture to the according uniform.
  16292. * @param channel The texture channel
  16293. * @param uniform The uniform to set
  16294. * @param texture The texture to apply
  16295. */
  16296. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16297. if (channel < 0) {
  16298. return;
  16299. }
  16300. if (uniform) {
  16301. this._boundUniforms[channel] = uniform;
  16302. }
  16303. this._setTexture(channel, texture);
  16304. };
  16305. /**
  16306. * Sets a depth stencil texture from a render target to the according uniform.
  16307. * @param channel The texture channel
  16308. * @param uniform The uniform to set
  16309. * @param texture The render target texture containing the depth stencil texture to apply
  16310. */
  16311. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16312. if (channel < 0) {
  16313. return;
  16314. }
  16315. if (uniform) {
  16316. this._boundUniforms[channel] = uniform;
  16317. }
  16318. if (!texture || !texture.depthStencilTexture) {
  16319. this._setTexture(channel, null);
  16320. }
  16321. else {
  16322. this._setTexture(channel, texture, false, true);
  16323. }
  16324. };
  16325. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16326. var uniform = this._boundUniforms[sourceSlot];
  16327. if (uniform._currentState === destination) {
  16328. return;
  16329. }
  16330. this._gl.uniform1i(uniform, destination);
  16331. uniform._currentState = destination;
  16332. };
  16333. Engine.prototype._getTextureWrapMode = function (mode) {
  16334. switch (mode) {
  16335. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16336. return this._gl.REPEAT;
  16337. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16338. return this._gl.CLAMP_TO_EDGE;
  16339. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16340. return this._gl.MIRRORED_REPEAT;
  16341. }
  16342. return this._gl.REPEAT;
  16343. };
  16344. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16345. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16346. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16347. // Not ready?
  16348. if (!texture) {
  16349. if (this._boundTexturesCache[channel] != null) {
  16350. this._activeChannel = channel;
  16351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16353. if (this.webGLVersion > 1) {
  16354. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16355. }
  16356. }
  16357. return false;
  16358. }
  16359. // Video
  16360. if (texture.video) {
  16361. this._activeChannel = channel;
  16362. texture.update();
  16363. }
  16364. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16365. texture.delayLoad();
  16366. return false;
  16367. }
  16368. var internalTexture;
  16369. if (depthStencilTexture) {
  16370. internalTexture = texture.depthStencilTexture;
  16371. }
  16372. else if (texture.isReady()) {
  16373. internalTexture = texture.getInternalTexture();
  16374. }
  16375. else if (texture.isCube) {
  16376. internalTexture = this.emptyCubeTexture;
  16377. }
  16378. else if (texture.is3D) {
  16379. internalTexture = this.emptyTexture3D;
  16380. }
  16381. else {
  16382. internalTexture = this.emptyTexture;
  16383. }
  16384. if (!isPartOfTextureArray) {
  16385. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16386. }
  16387. var needToBind = true;
  16388. if (this._boundTexturesCache[channel] === internalTexture) {
  16389. this._moveBoundTextureOnTop(internalTexture);
  16390. if (!isPartOfTextureArray) {
  16391. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16392. }
  16393. needToBind = false;
  16394. }
  16395. this._activeChannel = channel;
  16396. if (internalTexture && internalTexture.is3D) {
  16397. if (needToBind) {
  16398. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16399. }
  16400. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16401. internalTexture._cachedWrapU = texture.wrapU;
  16402. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16403. }
  16404. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16405. internalTexture._cachedWrapV = texture.wrapV;
  16406. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16407. }
  16408. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16409. internalTexture._cachedWrapR = texture.wrapR;
  16410. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16411. }
  16412. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16413. }
  16414. else if (internalTexture && internalTexture.isCube) {
  16415. if (needToBind) {
  16416. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16417. }
  16418. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16419. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16420. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16421. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16422. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16423. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16424. }
  16425. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16426. }
  16427. else {
  16428. if (needToBind) {
  16429. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16430. }
  16431. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16432. internalTexture._cachedWrapU = texture.wrapU;
  16433. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16434. }
  16435. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16436. internalTexture._cachedWrapV = texture.wrapV;
  16437. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16438. }
  16439. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16440. }
  16441. return true;
  16442. };
  16443. /**
  16444. * Sets an array of texture to the webGL context
  16445. * @param channel defines the channel where the texture array must be set
  16446. * @param uniform defines the associated uniform location
  16447. * @param textures defines the array of textures to bind
  16448. */
  16449. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16450. if (channel < 0 || !uniform) {
  16451. return;
  16452. }
  16453. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16454. this._textureUnits = new Int32Array(textures.length);
  16455. }
  16456. for (var i = 0; i < textures.length; i++) {
  16457. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16458. }
  16459. this._gl.uniform1iv(uniform, this._textureUnits);
  16460. for (var index = 0; index < textures.length; index++) {
  16461. this._setTexture(this._textureUnits[index], textures[index], true);
  16462. }
  16463. };
  16464. /** @hidden */
  16465. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16466. var internalTexture = texture.getInternalTexture();
  16467. if (!internalTexture) {
  16468. return;
  16469. }
  16470. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16471. var value = texture.anisotropicFilteringLevel;
  16472. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16473. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16474. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16475. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16476. }
  16477. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16478. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16479. internalTexture._cachedAnisotropicFilteringLevel = value;
  16480. }
  16481. };
  16482. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16483. this._bindTextureDirectly(target, texture, true, true);
  16484. this._gl.texParameterf(target, parameter, value);
  16485. };
  16486. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16487. if (texture) {
  16488. this._bindTextureDirectly(target, texture, true, true);
  16489. }
  16490. this._gl.texParameteri(target, parameter, value);
  16491. };
  16492. /**
  16493. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16494. * @param x defines the x coordinate of the rectangle where pixels must be read
  16495. * @param y defines the y coordinate of the rectangle where pixels must be read
  16496. * @param width defines the width of the rectangle where pixels must be read
  16497. * @param height defines the height of the rectangle where pixels must be read
  16498. * @returns a Uint8Array containing RGBA colors
  16499. */
  16500. Engine.prototype.readPixels = function (x, y, width, height) {
  16501. var data = new Uint8Array(height * width * 4);
  16502. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16503. return data;
  16504. };
  16505. /**
  16506. * Add an externaly attached data from its key.
  16507. * This method call will fail and return false, if such key already exists.
  16508. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16509. * @param key the unique key that identifies the data
  16510. * @param data the data object to associate to the key for this Engine instance
  16511. * @return true if no such key were already present and the data was added successfully, false otherwise
  16512. */
  16513. Engine.prototype.addExternalData = function (key, data) {
  16514. if (!this._externalData) {
  16515. this._externalData = new BABYLON.StringDictionary();
  16516. }
  16517. return this._externalData.add(key, data);
  16518. };
  16519. /**
  16520. * Get an externaly attached data from its key
  16521. * @param key the unique key that identifies the data
  16522. * @return the associated data, if present (can be null), or undefined if not present
  16523. */
  16524. Engine.prototype.getExternalData = function (key) {
  16525. if (!this._externalData) {
  16526. this._externalData = new BABYLON.StringDictionary();
  16527. }
  16528. return this._externalData.get(key);
  16529. };
  16530. /**
  16531. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16532. * @param key the unique key that identifies the data
  16533. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16534. * @return the associated data, can be null if the factory returned null.
  16535. */
  16536. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16537. if (!this._externalData) {
  16538. this._externalData = new BABYLON.StringDictionary();
  16539. }
  16540. return this._externalData.getOrAddWithFactory(key, factory);
  16541. };
  16542. /**
  16543. * Remove an externaly attached data from the Engine instance
  16544. * @param key the unique key that identifies the data
  16545. * @return true if the data was successfully removed, false if it doesn't exist
  16546. */
  16547. Engine.prototype.removeExternalData = function (key) {
  16548. if (!this._externalData) {
  16549. this._externalData = new BABYLON.StringDictionary();
  16550. }
  16551. return this._externalData.remove(key);
  16552. };
  16553. /**
  16554. * Unbind all vertex attributes from the webGL context
  16555. */
  16556. Engine.prototype.unbindAllAttributes = function () {
  16557. if (this._mustWipeVertexAttributes) {
  16558. this._mustWipeVertexAttributes = false;
  16559. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16560. this._gl.disableVertexAttribArray(i);
  16561. this._vertexAttribArraysEnabled[i] = false;
  16562. this._currentBufferPointers[i].active = false;
  16563. }
  16564. return;
  16565. }
  16566. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16567. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16568. continue;
  16569. }
  16570. this._gl.disableVertexAttribArray(i);
  16571. this._vertexAttribArraysEnabled[i] = false;
  16572. this._currentBufferPointers[i].active = false;
  16573. }
  16574. };
  16575. /**
  16576. * 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
  16577. */
  16578. Engine.prototype.releaseEffects = function () {
  16579. for (var name in this._compiledEffects) {
  16580. this._deleteProgram(this._compiledEffects[name]._program);
  16581. }
  16582. this._compiledEffects = {};
  16583. };
  16584. /**
  16585. * Dispose and release all associated resources
  16586. */
  16587. Engine.prototype.dispose = function () {
  16588. this.hideLoadingUI();
  16589. this.stopRenderLoop();
  16590. // Release postProcesses
  16591. while (this.postProcesses.length) {
  16592. this.postProcesses[0].dispose();
  16593. }
  16594. // Empty texture
  16595. if (this._emptyTexture) {
  16596. this._releaseTexture(this._emptyTexture);
  16597. this._emptyTexture = null;
  16598. }
  16599. if (this._emptyCubeTexture) {
  16600. this._releaseTexture(this._emptyCubeTexture);
  16601. this._emptyCubeTexture = null;
  16602. }
  16603. // Rescale PP
  16604. if (this._rescalePostProcess) {
  16605. this._rescalePostProcess.dispose();
  16606. }
  16607. // Release scenes
  16608. while (this.scenes.length) {
  16609. this.scenes[0].dispose();
  16610. }
  16611. // Release audio engine
  16612. if (Engine.audioEngine) {
  16613. Engine.audioEngine.dispose();
  16614. }
  16615. // Release effects
  16616. this.releaseEffects();
  16617. // Unbind
  16618. this.unbindAllAttributes();
  16619. this._boundUniforms = [];
  16620. if (this._dummyFramebuffer) {
  16621. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16622. }
  16623. //WebVR
  16624. this.disableVR();
  16625. // Events
  16626. if (BABYLON.Tools.IsWindowObjectExist()) {
  16627. window.removeEventListener("blur", this._onBlur);
  16628. window.removeEventListener("focus", this._onFocus);
  16629. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16630. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16631. if (this._renderingCanvas) {
  16632. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16633. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16634. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16635. if (!this._doNotHandleContextLost) {
  16636. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16637. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16638. }
  16639. }
  16640. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16641. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16642. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16643. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16644. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16645. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16646. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16647. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16648. if (this._onVrDisplayConnect) {
  16649. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16650. if (this._onVrDisplayDisconnect) {
  16651. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16652. }
  16653. if (this._onVrDisplayPresentChange) {
  16654. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16655. }
  16656. this._onVrDisplayConnect = null;
  16657. this._onVrDisplayDisconnect = null;
  16658. }
  16659. }
  16660. // Remove from Instances
  16661. var index = Engine.Instances.indexOf(this);
  16662. if (index >= 0) {
  16663. Engine.Instances.splice(index, 1);
  16664. }
  16665. this._workingCanvas = null;
  16666. this._workingContext = null;
  16667. this._currentBufferPointers = [];
  16668. this._renderingCanvas = null;
  16669. this._currentProgram = null;
  16670. this._bindedRenderFunction = null;
  16671. this.onResizeObservable.clear();
  16672. this.onCanvasBlurObservable.clear();
  16673. this.onCanvasFocusObservable.clear();
  16674. this.onCanvasPointerOutObservable.clear();
  16675. this.onBeginFrameObservable.clear();
  16676. this.onEndFrameObservable.clear();
  16677. BABYLON.Effect.ResetCache();
  16678. // Abort active requests
  16679. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16680. var request = _a[_i];
  16681. request.abort();
  16682. }
  16683. };
  16684. // Loading screen
  16685. /**
  16686. * Display the loading screen
  16687. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16688. */
  16689. Engine.prototype.displayLoadingUI = function () {
  16690. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16691. return;
  16692. }
  16693. var loadingScreen = this.loadingScreen;
  16694. if (loadingScreen) {
  16695. loadingScreen.displayLoadingUI();
  16696. }
  16697. };
  16698. /**
  16699. * Hide the loading screen
  16700. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16701. */
  16702. Engine.prototype.hideLoadingUI = function () {
  16703. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16704. return;
  16705. }
  16706. var loadingScreen = this.loadingScreen;
  16707. if (loadingScreen) {
  16708. loadingScreen.hideLoadingUI();
  16709. }
  16710. };
  16711. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16712. /**
  16713. * Gets the current loading screen object
  16714. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16715. */
  16716. get: function () {
  16717. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16718. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16719. return this._loadingScreen;
  16720. },
  16721. /**
  16722. * Sets the current loading screen object
  16723. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16724. */
  16725. set: function (loadingScreen) {
  16726. this._loadingScreen = loadingScreen;
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16732. /**
  16733. * Sets the current loading screen text
  16734. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16735. */
  16736. set: function (text) {
  16737. this.loadingScreen.loadingUIText = text;
  16738. },
  16739. enumerable: true,
  16740. configurable: true
  16741. });
  16742. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16743. /**
  16744. * Sets the current loading screen background color
  16745. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16746. */
  16747. set: function (color) {
  16748. this.loadingScreen.loadingUIBackgroundColor = color;
  16749. },
  16750. enumerable: true,
  16751. configurable: true
  16752. });
  16753. /**
  16754. * Attach a new callback raised when context lost event is fired
  16755. * @param callback defines the callback to call
  16756. */
  16757. Engine.prototype.attachContextLostEvent = function (callback) {
  16758. if (this._renderingCanvas) {
  16759. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16760. }
  16761. };
  16762. /**
  16763. * Attach a new callback raised when context restored event is fired
  16764. * @param callback defines the callback to call
  16765. */
  16766. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16767. if (this._renderingCanvas) {
  16768. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16769. }
  16770. };
  16771. /**
  16772. * Gets the source code of the vertex shader associated with a specific webGL program
  16773. * @param program defines the program to use
  16774. * @returns a string containing the source code of the vertex shader associated with the program
  16775. */
  16776. Engine.prototype.getVertexShaderSource = function (program) {
  16777. var shaders = this._gl.getAttachedShaders(program);
  16778. if (!shaders) {
  16779. return null;
  16780. }
  16781. return this._gl.getShaderSource(shaders[0]);
  16782. };
  16783. /**
  16784. * Gets the source code of the fragment shader associated with a specific webGL program
  16785. * @param program defines the program to use
  16786. * @returns a string containing the source code of the fragment shader associated with the program
  16787. */
  16788. Engine.prototype.getFragmentShaderSource = function (program) {
  16789. var shaders = this._gl.getAttachedShaders(program);
  16790. if (!shaders) {
  16791. return null;
  16792. }
  16793. return this._gl.getShaderSource(shaders[1]);
  16794. };
  16795. /**
  16796. * Get the current error code of the webGL context
  16797. * @returns the error code
  16798. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16799. */
  16800. Engine.prototype.getError = function () {
  16801. return this._gl.getError();
  16802. };
  16803. // FPS
  16804. /**
  16805. * Gets the current framerate
  16806. * @returns a number representing the framerate
  16807. */
  16808. Engine.prototype.getFps = function () {
  16809. return this._fps;
  16810. };
  16811. /**
  16812. * Gets the time spent between current and previous frame
  16813. * @returns a number representing the delta time in ms
  16814. */
  16815. Engine.prototype.getDeltaTime = function () {
  16816. return this._deltaTime;
  16817. };
  16818. Engine.prototype._measureFps = function () {
  16819. this._performanceMonitor.sampleFrame();
  16820. this._fps = this._performanceMonitor.averageFPS;
  16821. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16822. };
  16823. /** @hidden */
  16824. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16825. if (faceIndex === void 0) { faceIndex = -1; }
  16826. if (level === void 0) { level = 0; }
  16827. var gl = this._gl;
  16828. if (!this._dummyFramebuffer) {
  16829. var dummy = gl.createFramebuffer();
  16830. if (!dummy) {
  16831. throw new Error("Unable to create dummy framebuffer");
  16832. }
  16833. this._dummyFramebuffer = dummy;
  16834. }
  16835. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16836. if (faceIndex > -1) {
  16837. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16838. }
  16839. else {
  16840. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16841. }
  16842. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16843. var buffer;
  16844. switch (readType) {
  16845. case gl.UNSIGNED_BYTE:
  16846. buffer = new Uint8Array(4 * width * height);
  16847. readType = gl.UNSIGNED_BYTE;
  16848. break;
  16849. default:
  16850. buffer = new Float32Array(4 * width * height);
  16851. readType = gl.FLOAT;
  16852. break;
  16853. }
  16854. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16855. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16856. return buffer;
  16857. };
  16858. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16859. if (this._webGLVersion > 1) {
  16860. return this._caps.colorBufferFloat;
  16861. }
  16862. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16863. };
  16864. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16865. if (this._webGLVersion > 1) {
  16866. return this._caps.colorBufferFloat;
  16867. }
  16868. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16869. };
  16870. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16871. Engine.prototype._canRenderToFramebuffer = function (type) {
  16872. var gl = this._gl;
  16873. //clear existing errors
  16874. while (gl.getError() !== gl.NO_ERROR) { }
  16875. var successful = true;
  16876. var texture = gl.createTexture();
  16877. gl.bindTexture(gl.TEXTURE_2D, texture);
  16878. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16880. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16881. var fb = gl.createFramebuffer();
  16882. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16883. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16884. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16885. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16886. successful = successful && (gl.getError() === gl.NO_ERROR);
  16887. //try render by clearing frame buffer's color buffer
  16888. if (successful) {
  16889. gl.clear(gl.COLOR_BUFFER_BIT);
  16890. successful = successful && (gl.getError() === gl.NO_ERROR);
  16891. }
  16892. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16893. if (successful) {
  16894. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16895. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16896. var readFormat = gl.RGBA;
  16897. var readType = gl.UNSIGNED_BYTE;
  16898. var buffer = new Uint8Array(4);
  16899. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16900. successful = successful && (gl.getError() === gl.NO_ERROR);
  16901. }
  16902. //clean up
  16903. gl.deleteTexture(texture);
  16904. gl.deleteFramebuffer(fb);
  16905. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16906. //clear accumulated errors
  16907. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16908. return successful;
  16909. };
  16910. /** @hidden */
  16911. Engine.prototype._getWebGLTextureType = function (type) {
  16912. if (type === Engine.TEXTURETYPE_FLOAT) {
  16913. return this._gl.FLOAT;
  16914. }
  16915. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16916. // Add Half Float Constant.
  16917. return this._gl.HALF_FLOAT_OES;
  16918. }
  16919. return this._gl.UNSIGNED_BYTE;
  16920. };
  16921. ;
  16922. Engine.prototype._getInternalFormat = function (format) {
  16923. var internalFormat = this._gl.RGBA;
  16924. switch (format) {
  16925. case Engine.TEXTUREFORMAT_ALPHA:
  16926. internalFormat = this._gl.ALPHA;
  16927. break;
  16928. case Engine.TEXTUREFORMAT_LUMINANCE:
  16929. internalFormat = this._gl.LUMINANCE;
  16930. break;
  16931. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16932. internalFormat = this._gl.LUMINANCE_ALPHA;
  16933. break;
  16934. case Engine.TEXTUREFORMAT_RGB:
  16935. internalFormat = this._gl.RGB;
  16936. break;
  16937. case Engine.TEXTUREFORMAT_RGBA:
  16938. internalFormat = this._gl.RGBA;
  16939. break;
  16940. case Engine.TEXTUREFORMAT_R:
  16941. internalFormat = this._gl.RED;
  16942. break;
  16943. case Engine.TEXTUREFORMAT_RG:
  16944. internalFormat = this._gl.RG;
  16945. break;
  16946. }
  16947. return internalFormat;
  16948. };
  16949. /** @hidden */
  16950. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16951. if (this._webGLVersion === 1) {
  16952. if (format !== undefined) {
  16953. switch (format) {
  16954. case Engine.TEXTUREFORMAT_LUMINANCE:
  16955. return this._gl.LUMINANCE;
  16956. case Engine.TEXTUREFORMAT_ALPHA:
  16957. return this._gl.ALPHA;
  16958. }
  16959. }
  16960. return this._gl.RGBA;
  16961. }
  16962. if (type === Engine.TEXTURETYPE_FLOAT) {
  16963. if (format !== undefined) {
  16964. switch (format) {
  16965. case Engine.TEXTUREFORMAT_R:
  16966. return this._gl.R32F;
  16967. case Engine.TEXTUREFORMAT_RG:
  16968. return this._gl.RG32F;
  16969. case Engine.TEXTUREFORMAT_RGB:
  16970. return this._gl.RGB32F;
  16971. }
  16972. }
  16973. return this._gl.RGBA32F;
  16974. }
  16975. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16976. if (format) {
  16977. switch (format) {
  16978. case Engine.TEXTUREFORMAT_R:
  16979. return this._gl.R16F;
  16980. case Engine.TEXTUREFORMAT_RG:
  16981. return this._gl.RG16F;
  16982. case Engine.TEXTUREFORMAT_RGB:
  16983. return this._gl.RGB16F;
  16984. }
  16985. }
  16986. return this._gl.RGBA16F;
  16987. }
  16988. if (format !== undefined) {
  16989. switch (format) {
  16990. case Engine.TEXTUREFORMAT_LUMINANCE:
  16991. return this._gl.LUMINANCE;
  16992. case Engine.TEXTUREFORMAT_RGB:
  16993. return this._gl.RGB;
  16994. case Engine.TEXTUREFORMAT_R:
  16995. return this._gl.R8;
  16996. case Engine.TEXTUREFORMAT_RG:
  16997. return this._gl.RG8;
  16998. case Engine.TEXTUREFORMAT_ALPHA:
  16999. return this._gl.ALPHA;
  17000. }
  17001. }
  17002. return this._gl.RGBA;
  17003. };
  17004. ;
  17005. /** @hidden */
  17006. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17007. if (type === Engine.TEXTURETYPE_FLOAT) {
  17008. return this._gl.RGBA32F;
  17009. }
  17010. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17011. return this._gl.RGBA16F;
  17012. }
  17013. return this._gl.RGBA8;
  17014. };
  17015. ;
  17016. /** @hidden */
  17017. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17018. var _this = this;
  17019. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17020. this._activeRequests.push(request);
  17021. request.onCompleteObservable.add(function (request) {
  17022. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17023. });
  17024. return request;
  17025. };
  17026. /** @hidden */
  17027. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17028. var _this = this;
  17029. return new Promise(function (resolve, reject) {
  17030. _this._loadFile(url, function (data) {
  17031. resolve(data);
  17032. }, undefined, database, useArrayBuffer, function (request, exception) {
  17033. reject(exception);
  17034. });
  17035. });
  17036. };
  17037. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17038. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17039. var onload = function (data) {
  17040. loadedFiles[index] = data;
  17041. loadedFiles._internalCount++;
  17042. if (loadedFiles._internalCount === 6) {
  17043. onfinish(loadedFiles);
  17044. }
  17045. };
  17046. var onerror = function (request, exception) {
  17047. if (onErrorCallBack && request) {
  17048. onErrorCallBack(request.status + " " + request.statusText, exception);
  17049. }
  17050. };
  17051. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17052. };
  17053. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17054. if (onError === void 0) { onError = null; }
  17055. var loadedFiles = [];
  17056. loadedFiles._internalCount = 0;
  17057. for (var index = 0; index < 6; index++) {
  17058. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17059. }
  17060. };
  17061. // Statics
  17062. /**
  17063. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17064. * @returns true if the engine can be created
  17065. * @ignorenaming
  17066. */
  17067. Engine.isSupported = function () {
  17068. try {
  17069. var tempcanvas = document.createElement("canvas");
  17070. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17071. return gl != null && !!window.WebGLRenderingContext;
  17072. }
  17073. catch (e) {
  17074. return false;
  17075. }
  17076. };
  17077. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17078. Engine.ExceptionList = [
  17079. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17080. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17081. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17082. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17083. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17084. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17085. ];
  17086. /** Gets the list of created engines */
  17087. Engine.Instances = new Array();
  17088. // Const statics
  17089. /** Defines that alpha blending is disabled */
  17090. Engine.ALPHA_DISABLE = 0;
  17091. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17092. Engine.ALPHA_ADD = 1;
  17093. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17094. Engine.ALPHA_COMBINE = 2;
  17095. /** Defines that alpha blending to DEST - SRC * DEST */
  17096. Engine.ALPHA_SUBTRACT = 3;
  17097. /** Defines that alpha blending to SRC * DEST */
  17098. Engine.ALPHA_MULTIPLY = 4;
  17099. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17100. Engine.ALPHA_MAXIMIZED = 5;
  17101. /** Defines that alpha blending to SRC + DEST */
  17102. Engine.ALPHA_ONEONE = 6;
  17103. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17104. Engine.ALPHA_PREMULTIPLIED = 7;
  17105. /**
  17106. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17107. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17108. */
  17109. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17110. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17111. Engine.ALPHA_INTERPOLATE = 9;
  17112. /**
  17113. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17114. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17115. */
  17116. Engine.ALPHA_SCREENMODE = 10;
  17117. /** Defines that the ressource is not delayed*/
  17118. Engine.DELAYLOADSTATE_NONE = 0;
  17119. /** Defines that the ressource was successfully delay loaded */
  17120. Engine.DELAYLOADSTATE_LOADED = 1;
  17121. /** Defines that the ressource is currently delay loading */
  17122. Engine.DELAYLOADSTATE_LOADING = 2;
  17123. /** Defines that the ressource is delayed and has not started loading */
  17124. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17125. // Depht or Stencil test Constants.
  17126. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17127. Engine.NEVER = 0x0200;
  17128. /** 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 */
  17129. Engine.ALWAYS = 0x0207;
  17130. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17131. Engine.LESS = 0x0201;
  17132. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17133. Engine.EQUAL = 0x0202;
  17134. /** 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 */
  17135. Engine.LEQUAL = 0x0203;
  17136. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17137. Engine.GREATER = 0x0204;
  17138. /** 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 */
  17139. Engine.GEQUAL = 0x0206;
  17140. /** 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 */
  17141. Engine.NOTEQUAL = 0x0205;
  17142. // Stencil Actions Constants.
  17143. /** Passed to stencilOperation to specify that stencil value must be kept */
  17144. Engine.KEEP = 0x1E00;
  17145. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17146. Engine.REPLACE = 0x1E01;
  17147. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17148. Engine.INCR = 0x1E02;
  17149. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17150. Engine.DECR = 0x1E03;
  17151. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17152. Engine.INVERT = 0x150A;
  17153. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17154. Engine.INCR_WRAP = 0x8507;
  17155. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17156. Engine.DECR_WRAP = 0x8508;
  17157. /** Texture is not repeating outside of 0..1 UVs */
  17158. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17159. /** Texture is repeating outside of 0..1 UVs */
  17160. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17161. /** Texture is repeating and mirrored */
  17162. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17163. /** ALPHA */
  17164. Engine.TEXTUREFORMAT_ALPHA = 0;
  17165. /** LUMINANCE */
  17166. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17167. /** LUMINANCE_ALPHA */
  17168. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17169. /** RGB */
  17170. Engine.TEXTUREFORMAT_RGB = 4;
  17171. /** RGBA */
  17172. Engine.TEXTUREFORMAT_RGBA = 5;
  17173. /** R */
  17174. Engine.TEXTUREFORMAT_R = 6;
  17175. /** RG */
  17176. Engine.TEXTUREFORMAT_RG = 7;
  17177. /** UNSIGNED_INT */
  17178. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17179. /** FLOAT */
  17180. Engine.TEXTURETYPE_FLOAT = 1;
  17181. /** HALF_FLOAT */
  17182. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17183. /** nearest is mag = nearest and min = nearest and mip = linear */
  17184. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17185. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17186. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17187. /** Trilinear is mag = linear and min = linear and mip = linear */
  17188. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17189. /** nearest is mag = nearest and min = nearest and mip = linear */
  17190. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17191. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17192. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17193. /** Trilinear is mag = linear and min = linear and mip = linear */
  17194. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17195. /** mag = nearest and min = nearest and mip = nearest */
  17196. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17197. /** mag = nearest and min = linear and mip = nearest */
  17198. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17199. /** mag = nearest and min = linear and mip = linear */
  17200. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17201. /** mag = nearest and min = linear and mip = none */
  17202. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17203. /** mag = nearest and min = nearest and mip = none */
  17204. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17205. /** mag = linear and min = nearest and mip = nearest */
  17206. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17207. /** mag = linear and min = nearest and mip = linear */
  17208. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17209. /** mag = linear and min = linear and mip = none */
  17210. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17211. /** mag = linear and min = nearest and mip = none */
  17212. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17213. /** Explicit coordinates mode */
  17214. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17215. /** Spherical coordinates mode */
  17216. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17217. /** Planar coordinates mode */
  17218. Engine.TEXTURE_PLANAR_MODE = 2;
  17219. /** Cubic coordinates mode */
  17220. Engine.TEXTURE_CUBIC_MODE = 3;
  17221. /** Projection coordinates mode */
  17222. Engine.TEXTURE_PROJECTION_MODE = 4;
  17223. /** Skybox coordinates mode */
  17224. Engine.TEXTURE_SKYBOX_MODE = 5;
  17225. /** Inverse Cubic coordinates mode */
  17226. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17227. /** Equirectangular coordinates mode */
  17228. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17229. /** Equirectangular Fixed coordinates mode */
  17230. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17231. /** Equirectangular Fixed Mirrored coordinates mode */
  17232. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17233. // Texture rescaling mode
  17234. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17235. Engine.SCALEMODE_FLOOR = 1;
  17236. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17237. Engine.SCALEMODE_NEAREST = 2;
  17238. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17239. Engine.SCALEMODE_CEILING = 3;
  17240. // Updatable statics so stick with vars here
  17241. /**
  17242. * Gets or sets the epsilon value used by collision engine
  17243. */
  17244. Engine.CollisionsEpsilon = 0.001;
  17245. /**
  17246. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17247. */
  17248. Engine.CodeRepository = "src/";
  17249. /**
  17250. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17251. */
  17252. Engine.ShadersRepository = "src/Shaders/";
  17253. return Engine;
  17254. }());
  17255. BABYLON.Engine = Engine;
  17256. })(BABYLON || (BABYLON = {}));
  17257. //# sourceMappingURL=babylon.engine.js.map
  17258. var BABYLON;
  17259. (function (BABYLON) {
  17260. /**
  17261. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17262. */
  17263. var Node = /** @class */ (function () {
  17264. /**
  17265. * Creates a new Node
  17266. * @param {string} name - the name and id to be given to this node
  17267. * @param {BABYLON.Scene} the scene this node will be added to
  17268. */
  17269. function Node(name, scene) {
  17270. if (scene === void 0) { scene = null; }
  17271. /**
  17272. * Gets or sets a string used to store user defined state for the node
  17273. */
  17274. this.state = "";
  17275. /**
  17276. * Gets or sets an object used to store user defined information for the node
  17277. */
  17278. this.metadata = null;
  17279. /**
  17280. * Gets or sets a boolean used to define if the node must be serialized
  17281. */
  17282. this.doNotSerialize = false;
  17283. /** @hidden */
  17284. this._isDisposed = false;
  17285. /**
  17286. * Gets a list of Animations associated with the node
  17287. */
  17288. this.animations = new Array();
  17289. this._ranges = {};
  17290. this._isEnabled = true;
  17291. this._isReady = true;
  17292. /** @hidden */
  17293. this._currentRenderId = -1;
  17294. this._parentRenderId = -1;
  17295. this._childRenderId = -1;
  17296. this._animationPropertiesOverride = null;
  17297. /**
  17298. * An event triggered when the mesh is disposed
  17299. */
  17300. this.onDisposeObservable = new BABYLON.Observable();
  17301. // Behaviors
  17302. this._behaviors = new Array();
  17303. this.name = name;
  17304. this.id = name;
  17305. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17306. this.uniqueId = this._scene.getUniqueId();
  17307. this._initCache();
  17308. }
  17309. /**
  17310. * Add a new node constructor
  17311. * @param type defines the type name of the node to construct
  17312. * @param constructorFunc defines the constructor function
  17313. */
  17314. Node.AddNodeConstructor = function (type, constructorFunc) {
  17315. this._NodeConstructors[type] = constructorFunc;
  17316. };
  17317. /**
  17318. * Returns a node constructor based on type name
  17319. * @param type defines the type name
  17320. * @param name defines the new node name
  17321. * @param scene defines the hosting scene
  17322. * @param options defines optional options to transmit to constructors
  17323. * @returns the new constructor or null
  17324. */
  17325. Node.Construct = function (type, name, scene, options) {
  17326. var constructorFunc = this._NodeConstructors[type];
  17327. if (!constructorFunc) {
  17328. return null;
  17329. }
  17330. return constructorFunc(name, scene, options);
  17331. };
  17332. /**
  17333. * Gets a boolean indicating if the node has been disposed
  17334. * @returns true if the node was disposed
  17335. */
  17336. Node.prototype.isDisposed = function () {
  17337. return this._isDisposed;
  17338. };
  17339. Object.defineProperty(Node.prototype, "parent", {
  17340. get: function () {
  17341. return this._parentNode;
  17342. },
  17343. /**
  17344. * Gets or sets the parent of the node
  17345. */
  17346. set: function (parent) {
  17347. if (this._parentNode === parent) {
  17348. return;
  17349. }
  17350. // Remove self from list of children of parent
  17351. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17352. var index = this._parentNode._children.indexOf(this);
  17353. if (index !== -1) {
  17354. this._parentNode._children.splice(index, 1);
  17355. }
  17356. }
  17357. // Store new parent
  17358. this._parentNode = parent;
  17359. // Add as child to new parent
  17360. if (this._parentNode) {
  17361. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17362. this._parentNode._children = new Array();
  17363. }
  17364. this._parentNode._children.push(this);
  17365. }
  17366. },
  17367. enumerable: true,
  17368. configurable: true
  17369. });
  17370. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17371. /**
  17372. * Gets or sets the animation properties override
  17373. */
  17374. get: function () {
  17375. if (!this._animationPropertiesOverride) {
  17376. return this._scene.animationPropertiesOverride;
  17377. }
  17378. return this._animationPropertiesOverride;
  17379. },
  17380. set: function (value) {
  17381. this._animationPropertiesOverride = value;
  17382. },
  17383. enumerable: true,
  17384. configurable: true
  17385. });
  17386. /**
  17387. * Gets a string idenfifying the name of the class
  17388. * @returns "Node" string
  17389. */
  17390. Node.prototype.getClassName = function () {
  17391. return "Node";
  17392. };
  17393. Object.defineProperty(Node.prototype, "onDispose", {
  17394. /**
  17395. * Sets a callback that will be raised when the node will be disposed
  17396. */
  17397. set: function (callback) {
  17398. if (this._onDisposeObserver) {
  17399. this.onDisposeObservable.remove(this._onDisposeObserver);
  17400. }
  17401. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17402. },
  17403. enumerable: true,
  17404. configurable: true
  17405. });
  17406. /**
  17407. * Gets the scene of the node
  17408. * @returns a {BABYLON.Scene}
  17409. */
  17410. Node.prototype.getScene = function () {
  17411. return this._scene;
  17412. };
  17413. /**
  17414. * Gets the engine of the node
  17415. * @returns a {BABYLON.Engine}
  17416. */
  17417. Node.prototype.getEngine = function () {
  17418. return this._scene.getEngine();
  17419. };
  17420. /**
  17421. * Attach a behavior to the node
  17422. * @see http://doc.babylonjs.com/features/behaviour
  17423. * @param behavior defines the behavior to attach
  17424. * @returns the current Node
  17425. */
  17426. Node.prototype.addBehavior = function (behavior) {
  17427. var _this = this;
  17428. var index = this._behaviors.indexOf(behavior);
  17429. if (index !== -1) {
  17430. return this;
  17431. }
  17432. behavior.init();
  17433. if (this._scene.isLoading) {
  17434. // We defer the attach when the scene will be loaded
  17435. this._scene.onDataLoadedObservable.addOnce(function () {
  17436. behavior.attach(_this);
  17437. });
  17438. }
  17439. else {
  17440. behavior.attach(this);
  17441. }
  17442. this._behaviors.push(behavior);
  17443. return this;
  17444. };
  17445. /**
  17446. * Remove an attached behavior
  17447. * @see http://doc.babylonjs.com/features/behaviour
  17448. * @param behavior defines the behavior to attach
  17449. * @returns the current Node
  17450. */
  17451. Node.prototype.removeBehavior = function (behavior) {
  17452. var index = this._behaviors.indexOf(behavior);
  17453. if (index === -1) {
  17454. return this;
  17455. }
  17456. this._behaviors[index].detach();
  17457. this._behaviors.splice(index, 1);
  17458. return this;
  17459. };
  17460. Object.defineProperty(Node.prototype, "behaviors", {
  17461. /**
  17462. * Gets the list of attached behaviors
  17463. * @see http://doc.babylonjs.com/features/behaviour
  17464. */
  17465. get: function () {
  17466. return this._behaviors;
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. /**
  17472. * Gets an attached behavior by name
  17473. * @param name defines the name of the behavior to look for
  17474. * @see http://doc.babylonjs.com/features/behaviour
  17475. * @returns null if behavior was not found else the requested behavior
  17476. */
  17477. Node.prototype.getBehaviorByName = function (name) {
  17478. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17479. var behavior = _a[_i];
  17480. if (behavior.name === name) {
  17481. return behavior;
  17482. }
  17483. }
  17484. return null;
  17485. };
  17486. /**
  17487. * Returns the world matrix of the node
  17488. * @returns a matrix containing the node's world matrix
  17489. */
  17490. Node.prototype.getWorldMatrix = function () {
  17491. return BABYLON.Matrix.Identity();
  17492. };
  17493. /** @hidden */
  17494. Node.prototype._getWorldMatrixDeterminant = function () {
  17495. return 1;
  17496. };
  17497. // override it in derived class if you add new variables to the cache
  17498. // and call the parent class method
  17499. /** @hidden */
  17500. Node.prototype._initCache = function () {
  17501. this._cache = {};
  17502. this._cache.parent = undefined;
  17503. };
  17504. /** @hidden */
  17505. Node.prototype.updateCache = function (force) {
  17506. if (!force && this.isSynchronized())
  17507. return;
  17508. this._cache.parent = this.parent;
  17509. this._updateCache();
  17510. };
  17511. // override it in derived class if you add new variables to the cache
  17512. // and call the parent class method if !ignoreParentClass
  17513. /** @hidden */
  17514. Node.prototype._updateCache = function (ignoreParentClass) {
  17515. };
  17516. // override it in derived class if you add new variables to the cache
  17517. /** @hidden */
  17518. Node.prototype._isSynchronized = function () {
  17519. return true;
  17520. };
  17521. /** @hidden */
  17522. Node.prototype._markSyncedWithParent = function () {
  17523. if (this.parent) {
  17524. this._parentRenderId = this.parent._childRenderId;
  17525. }
  17526. };
  17527. /** @hidden */
  17528. Node.prototype.isSynchronizedWithParent = function () {
  17529. if (!this.parent) {
  17530. return true;
  17531. }
  17532. if (this._parentRenderId !== this.parent._childRenderId) {
  17533. return false;
  17534. }
  17535. return this.parent.isSynchronized();
  17536. };
  17537. /** @hidden */
  17538. Node.prototype.isSynchronized = function (updateCache) {
  17539. var check = this.hasNewParent();
  17540. check = check || !this.isSynchronizedWithParent();
  17541. check = check || !this._isSynchronized();
  17542. if (updateCache)
  17543. this.updateCache(true);
  17544. return !check;
  17545. };
  17546. /** @hidden */
  17547. Node.prototype.hasNewParent = function (update) {
  17548. if (this._cache.parent === this.parent)
  17549. return false;
  17550. if (update)
  17551. this._cache.parent = this.parent;
  17552. return true;
  17553. };
  17554. /**
  17555. * Is this node ready to be used/rendered
  17556. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17557. * @return true if the node is ready
  17558. */
  17559. Node.prototype.isReady = function (completeCheck) {
  17560. if (completeCheck === void 0) { completeCheck = false; }
  17561. return this._isReady;
  17562. };
  17563. /**
  17564. * Is this node enabled?
  17565. * 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
  17566. * @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
  17567. * @return whether this node (and its parent) is enabled
  17568. */
  17569. Node.prototype.isEnabled = function (checkAncestors) {
  17570. if (checkAncestors === void 0) { checkAncestors = true; }
  17571. if (checkAncestors === false) {
  17572. return this._isEnabled;
  17573. }
  17574. if (this._isEnabled === false) {
  17575. return false;
  17576. }
  17577. if (this.parent !== undefined && this.parent !== null) {
  17578. return this.parent.isEnabled(checkAncestors);
  17579. }
  17580. return true;
  17581. };
  17582. /**
  17583. * Set the enabled state of this node
  17584. * @param value defines the new enabled state
  17585. */
  17586. Node.prototype.setEnabled = function (value) {
  17587. this._isEnabled = value;
  17588. };
  17589. /**
  17590. * Is this node a descendant of the given node?
  17591. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17592. * @param ancestor defines the parent node to inspect
  17593. * @returns a boolean indicating if this node is a descendant of the given node
  17594. */
  17595. Node.prototype.isDescendantOf = function (ancestor) {
  17596. if (this.parent) {
  17597. if (this.parent === ancestor) {
  17598. return true;
  17599. }
  17600. return this.parent.isDescendantOf(ancestor);
  17601. }
  17602. return false;
  17603. };
  17604. /** @hidden */
  17605. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17606. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17607. if (!this._children) {
  17608. return;
  17609. }
  17610. for (var index = 0; index < this._children.length; index++) {
  17611. var item = this._children[index];
  17612. if (!predicate || predicate(item)) {
  17613. results.push(item);
  17614. }
  17615. if (!directDescendantsOnly) {
  17616. item._getDescendants(results, false, predicate);
  17617. }
  17618. }
  17619. };
  17620. /**
  17621. * Will return all nodes that have this node as ascendant
  17622. * @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
  17623. * @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
  17624. * @return all children nodes of all types
  17625. */
  17626. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17627. var results = new Array();
  17628. this._getDescendants(results, directDescendantsOnly, predicate);
  17629. return results;
  17630. };
  17631. /**
  17632. * Get all child-meshes of this node
  17633. * @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
  17634. * @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
  17635. * @returns an array of {BABYLON.AbstractMesh}
  17636. */
  17637. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17638. var results = [];
  17639. this._getDescendants(results, directDescendantsOnly, function (node) {
  17640. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17641. });
  17642. return results;
  17643. };
  17644. /**
  17645. * Get all child-transformNodes of this node
  17646. * @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
  17647. * @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
  17648. * @returns an array of {BABYLON.TransformNode}
  17649. */
  17650. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17651. var results = [];
  17652. this._getDescendants(results, directDescendantsOnly, function (node) {
  17653. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17654. });
  17655. return results;
  17656. };
  17657. /**
  17658. * Get all direct children of this node
  17659. * @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
  17660. * @returns an array of {BABYLON.Node}
  17661. */
  17662. Node.prototype.getChildren = function (predicate) {
  17663. return this.getDescendants(true, predicate);
  17664. };
  17665. /** @hidden */
  17666. Node.prototype._setReady = function (state) {
  17667. if (state === this._isReady) {
  17668. return;
  17669. }
  17670. if (!state) {
  17671. this._isReady = false;
  17672. return;
  17673. }
  17674. if (this.onReady) {
  17675. this.onReady(this);
  17676. }
  17677. this._isReady = true;
  17678. };
  17679. /**
  17680. * Get an animation by name
  17681. * @param name defines the name of the animation to look for
  17682. * @returns null if not found else the requested animation
  17683. */
  17684. Node.prototype.getAnimationByName = function (name) {
  17685. for (var i = 0; i < this.animations.length; i++) {
  17686. var animation = this.animations[i];
  17687. if (animation.name === name) {
  17688. return animation;
  17689. }
  17690. }
  17691. return null;
  17692. };
  17693. /**
  17694. * Creates an animation range for this node
  17695. * @param name defines the name of the range
  17696. * @param from defines the starting key
  17697. * @param to defines the end key
  17698. */
  17699. Node.prototype.createAnimationRange = function (name, from, to) {
  17700. // check name not already in use
  17701. if (!this._ranges[name]) {
  17702. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17703. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17704. if (this.animations[i]) {
  17705. this.animations[i].createRange(name, from, to);
  17706. }
  17707. }
  17708. }
  17709. };
  17710. /**
  17711. * Delete a specific animation range
  17712. * @param name defines the name of the range to delete
  17713. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17714. */
  17715. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17716. if (deleteFrames === void 0) { deleteFrames = true; }
  17717. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17718. if (this.animations[i]) {
  17719. this.animations[i].deleteRange(name, deleteFrames);
  17720. }
  17721. }
  17722. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17723. };
  17724. /**
  17725. * Get an animation range by name
  17726. * @param name defines the name of the animation range to look for
  17727. * @returns null if not found else the requested animation range
  17728. */
  17729. Node.prototype.getAnimationRange = function (name) {
  17730. return this._ranges[name];
  17731. };
  17732. /**
  17733. * Will start the animation sequence
  17734. * @param name defines the range frames for animation sequence
  17735. * @param loop defines if the animation should loop (false by default)
  17736. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17737. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17738. * @returns the object created for this animation. If range does not exist, it will return null
  17739. */
  17740. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17741. var range = this.getAnimationRange(name);
  17742. if (!range) {
  17743. return null;
  17744. }
  17745. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17746. };
  17747. /**
  17748. * Serialize animation ranges into a JSON compatible object
  17749. * @returns serialization object
  17750. */
  17751. Node.prototype.serializeAnimationRanges = function () {
  17752. var serializationRanges = [];
  17753. for (var name in this._ranges) {
  17754. var localRange = this._ranges[name];
  17755. if (!localRange) {
  17756. continue;
  17757. }
  17758. var range = {};
  17759. range.name = name;
  17760. range.from = localRange.from;
  17761. range.to = localRange.to;
  17762. serializationRanges.push(range);
  17763. }
  17764. return serializationRanges;
  17765. };
  17766. /**
  17767. * Computes the world matrix of the node
  17768. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17769. * @returns the world matrix
  17770. */
  17771. Node.prototype.computeWorldMatrix = function (force) {
  17772. return BABYLON.Matrix.Identity();
  17773. };
  17774. /**
  17775. * Releases resources associated with this node.
  17776. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17777. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17778. */
  17779. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17780. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17781. if (!doNotRecurse) {
  17782. var nodes = this.getDescendants(true);
  17783. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17784. var node = nodes_1[_i];
  17785. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17786. }
  17787. }
  17788. else {
  17789. var transformNodes = this.getChildTransformNodes(true);
  17790. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17791. var transformNode = transformNodes_1[_a];
  17792. transformNode.parent = null;
  17793. transformNode.computeWorldMatrix(true);
  17794. }
  17795. }
  17796. this.parent = null;
  17797. // Callback
  17798. this.onDisposeObservable.notifyObservers(this);
  17799. this.onDisposeObservable.clear();
  17800. // Behaviors
  17801. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17802. var behavior = _c[_b];
  17803. behavior.detach();
  17804. }
  17805. this._behaviors = [];
  17806. this._isDisposed = true;
  17807. };
  17808. /**
  17809. * Parse animation range data from a serialization object and store them into a given node
  17810. * @param node defines where to store the animation ranges
  17811. * @param parsedNode defines the serialization object to read data from
  17812. * @param scene defines the hosting scene
  17813. */
  17814. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17815. if (parsedNode.ranges) {
  17816. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17817. var data = parsedNode.ranges[index];
  17818. node.createAnimationRange(data.name, data.from, data.to);
  17819. }
  17820. }
  17821. };
  17822. Node._NodeConstructors = {};
  17823. __decorate([
  17824. BABYLON.serialize()
  17825. ], Node.prototype, "name", void 0);
  17826. __decorate([
  17827. BABYLON.serialize()
  17828. ], Node.prototype, "id", void 0);
  17829. __decorate([
  17830. BABYLON.serialize()
  17831. ], Node.prototype, "uniqueId", void 0);
  17832. __decorate([
  17833. BABYLON.serialize()
  17834. ], Node.prototype, "state", void 0);
  17835. __decorate([
  17836. BABYLON.serialize()
  17837. ], Node.prototype, "metadata", void 0);
  17838. return Node;
  17839. }());
  17840. BABYLON.Node = Node;
  17841. })(BABYLON || (BABYLON = {}));
  17842. //# sourceMappingURL=babylon.node.js.map
  17843. var BABYLON;
  17844. (function (BABYLON) {
  17845. var BoundingSphere = /** @class */ (function () {
  17846. /**
  17847. * Creates a new bounding sphere
  17848. * @param min defines the minimum vector (in local space)
  17849. * @param max defines the maximum vector (in local space)
  17850. */
  17851. function BoundingSphere(min, max) {
  17852. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17853. this.reConstruct(min, max);
  17854. }
  17855. /**
  17856. * Recreates the entire bounding sphere from scratch
  17857. * @param min defines the new minimum vector (in local space)
  17858. * @param max defines the new maximum vector (in local space)
  17859. */
  17860. BoundingSphere.prototype.reConstruct = function (min, max) {
  17861. this.minimum = min.clone();
  17862. this.maximum = max.clone();
  17863. var distance = BABYLON.Vector3.Distance(min, max);
  17864. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17865. this.radius = distance * 0.5;
  17866. this.centerWorld = BABYLON.Vector3.Zero();
  17867. this._update(BABYLON.Matrix.Identity());
  17868. };
  17869. /**
  17870. * Scale the current bounding sphere by applying a scale factor
  17871. * @param factor defines the scale factor to apply
  17872. * @returns the current bounding box
  17873. */
  17874. BoundingSphere.prototype.scale = function (factor) {
  17875. var newRadius = this.radius * factor;
  17876. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17877. var min = this.center.subtract(newRadiusVector);
  17878. var max = this.center.add(newRadiusVector);
  17879. this.reConstruct(min, max);
  17880. return this;
  17881. };
  17882. // Methods
  17883. BoundingSphere.prototype._update = function (world) {
  17884. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17885. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17886. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17887. };
  17888. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17889. for (var i = 0; i < 6; i++) {
  17890. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17891. return false;
  17892. }
  17893. return true;
  17894. };
  17895. BoundingSphere.prototype.intersectsPoint = function (point) {
  17896. var x = this.centerWorld.x - point.x;
  17897. var y = this.centerWorld.y - point.y;
  17898. var z = this.centerWorld.z - point.z;
  17899. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17900. if (this.radiusWorld < distance)
  17901. return false;
  17902. return true;
  17903. };
  17904. // Statics
  17905. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17906. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17907. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17908. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17909. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17910. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17911. return false;
  17912. return true;
  17913. };
  17914. return BoundingSphere;
  17915. }());
  17916. BABYLON.BoundingSphere = BoundingSphere;
  17917. })(BABYLON || (BABYLON = {}));
  17918. //# sourceMappingURL=babylon.boundingSphere.js.map
  17919. var BABYLON;
  17920. (function (BABYLON) {
  17921. var BoundingBox = /** @class */ (function () {
  17922. /**
  17923. * Creates a new bounding box
  17924. * @param min defines the minimum vector (in local space)
  17925. * @param max defines the maximum vector (in local space)
  17926. */
  17927. function BoundingBox(min, max) {
  17928. this.vectorsWorld = new Array();
  17929. this.reConstruct(min, max);
  17930. }
  17931. // Methods
  17932. /**
  17933. * Recreates the entire bounding box from scratch
  17934. * @param min defines the new minimum vector (in local space)
  17935. * @param max defines the new maximum vector (in local space)
  17936. */
  17937. BoundingBox.prototype.reConstruct = function (min, max) {
  17938. this.minimum = min.clone();
  17939. this.maximum = max.clone();
  17940. // Bounding vectors
  17941. this.vectors = new Array();
  17942. this.vectors.push(this.minimum.clone());
  17943. this.vectors.push(this.maximum.clone());
  17944. this.vectors.push(this.minimum.clone());
  17945. this.vectors[2].x = this.maximum.x;
  17946. this.vectors.push(this.minimum.clone());
  17947. this.vectors[3].y = this.maximum.y;
  17948. this.vectors.push(this.minimum.clone());
  17949. this.vectors[4].z = this.maximum.z;
  17950. this.vectors.push(this.maximum.clone());
  17951. this.vectors[5].z = this.minimum.z;
  17952. this.vectors.push(this.maximum.clone());
  17953. this.vectors[6].x = this.minimum.x;
  17954. this.vectors.push(this.maximum.clone());
  17955. this.vectors[7].y = this.minimum.y;
  17956. // OBB
  17957. this.center = this.maximum.add(this.minimum).scale(0.5);
  17958. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17959. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17960. // World
  17961. for (var index = 0; index < this.vectors.length; index++) {
  17962. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17963. }
  17964. this.minimumWorld = BABYLON.Vector3.Zero();
  17965. this.maximumWorld = BABYLON.Vector3.Zero();
  17966. this.centerWorld = BABYLON.Vector3.Zero();
  17967. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17968. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17969. };
  17970. /**
  17971. * Scale the current bounding box by applying a scale factor
  17972. * @param factor defines the scale factor to apply
  17973. * @returns the current bounding box
  17974. */
  17975. BoundingBox.prototype.scale = function (factor) {
  17976. var diff = this.maximum.subtract(this.minimum);
  17977. var distance = diff.length() * factor;
  17978. diff.normalize();
  17979. var newRadius = diff.scale(distance / 2);
  17980. var min = this.center.subtract(newRadius);
  17981. var max = this.center.add(newRadius);
  17982. this.reConstruct(min, max);
  17983. return this;
  17984. };
  17985. BoundingBox.prototype.getWorldMatrix = function () {
  17986. return this._worldMatrix;
  17987. };
  17988. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17989. this._worldMatrix.copyFrom(matrix);
  17990. return this;
  17991. };
  17992. BoundingBox.prototype._update = function (world) {
  17993. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17994. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17995. for (var index = 0; index < this.vectors.length; index++) {
  17996. var v = this.vectorsWorld[index];
  17997. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17998. if (v.x < this.minimumWorld.x)
  17999. this.minimumWorld.x = v.x;
  18000. if (v.y < this.minimumWorld.y)
  18001. this.minimumWorld.y = v.y;
  18002. if (v.z < this.minimumWorld.z)
  18003. this.minimumWorld.z = v.z;
  18004. if (v.x > this.maximumWorld.x)
  18005. this.maximumWorld.x = v.x;
  18006. if (v.y > this.maximumWorld.y)
  18007. this.maximumWorld.y = v.y;
  18008. if (v.z > this.maximumWorld.z)
  18009. this.maximumWorld.z = v.z;
  18010. }
  18011. // Extend
  18012. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18013. this.extendSizeWorld.scaleInPlace(0.5);
  18014. // OBB
  18015. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18016. this.centerWorld.scaleInPlace(0.5);
  18017. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18018. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18019. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18020. this._worldMatrix = world;
  18021. };
  18022. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18023. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18024. };
  18025. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18026. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18027. };
  18028. BoundingBox.prototype.intersectsPoint = function (point) {
  18029. var delta = -BABYLON.Epsilon;
  18030. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18031. return false;
  18032. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18033. return false;
  18034. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18035. return false;
  18036. return true;
  18037. };
  18038. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18039. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18040. };
  18041. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18042. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18043. return false;
  18044. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18045. return false;
  18046. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18047. return false;
  18048. return true;
  18049. };
  18050. // Statics
  18051. BoundingBox.Intersects = function (box0, box1) {
  18052. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18053. return false;
  18054. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18055. return false;
  18056. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18057. return false;
  18058. return true;
  18059. };
  18060. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18061. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18062. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18063. return (num <= (sphereRadius * sphereRadius));
  18064. };
  18065. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18066. for (var p = 0; p < 6; p++) {
  18067. for (var i = 0; i < 8; i++) {
  18068. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18069. return false;
  18070. }
  18071. }
  18072. }
  18073. return true;
  18074. };
  18075. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18076. for (var p = 0; p < 6; p++) {
  18077. var inCount = 8;
  18078. for (var i = 0; i < 8; i++) {
  18079. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18080. --inCount;
  18081. }
  18082. else {
  18083. break;
  18084. }
  18085. }
  18086. if (inCount === 0)
  18087. return false;
  18088. }
  18089. return true;
  18090. };
  18091. return BoundingBox;
  18092. }());
  18093. BABYLON.BoundingBox = BoundingBox;
  18094. })(BABYLON || (BABYLON = {}));
  18095. //# sourceMappingURL=babylon.boundingBox.js.map
  18096. var BABYLON;
  18097. (function (BABYLON) {
  18098. var computeBoxExtents = function (axis, box) {
  18099. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18100. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18101. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18102. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18103. var r = r0 + r1 + r2;
  18104. return {
  18105. min: p - r,
  18106. max: p + r
  18107. };
  18108. };
  18109. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18110. var axisOverlap = function (axis, box0, box1) {
  18111. var result0 = computeBoxExtents(axis, box0);
  18112. var result1 = computeBoxExtents(axis, box1);
  18113. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18114. };
  18115. var BoundingInfo = /** @class */ (function () {
  18116. function BoundingInfo(minimum, maximum) {
  18117. this.minimum = minimum;
  18118. this.maximum = maximum;
  18119. this._isLocked = false;
  18120. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18121. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18122. }
  18123. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18124. get: function () {
  18125. return this._isLocked;
  18126. },
  18127. set: function (value) {
  18128. this._isLocked = value;
  18129. },
  18130. enumerable: true,
  18131. configurable: true
  18132. });
  18133. // Methods
  18134. BoundingInfo.prototype.update = function (world) {
  18135. if (this._isLocked) {
  18136. return;
  18137. }
  18138. this.boundingBox._update(world);
  18139. this.boundingSphere._update(world);
  18140. };
  18141. /**
  18142. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18143. * @param center New center of the bounding info
  18144. * @param extend New extend of the bounding info
  18145. */
  18146. BoundingInfo.prototype.centerOn = function (center, extend) {
  18147. this.minimum = center.subtract(extend);
  18148. this.maximum = center.add(extend);
  18149. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18150. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18151. return this;
  18152. };
  18153. /**
  18154. * Scale the current bounding info by applying a scale factor
  18155. * @param factor defines the scale factor to apply
  18156. * @returns the current bounding info
  18157. */
  18158. BoundingInfo.prototype.scale = function (factor) {
  18159. this.boundingBox.scale(factor);
  18160. this.boundingSphere.scale(factor);
  18161. return this;
  18162. };
  18163. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18164. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18165. return false;
  18166. return this.boundingBox.isInFrustum(frustumPlanes);
  18167. };
  18168. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18169. /**
  18170. * Gets the world distance between the min and max points of the bounding box
  18171. */
  18172. get: function () {
  18173. var boundingBox = this.boundingBox;
  18174. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18175. return size.length();
  18176. },
  18177. enumerable: true,
  18178. configurable: true
  18179. });
  18180. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18181. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18182. };
  18183. BoundingInfo.prototype._checkCollision = function (collider) {
  18184. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18185. };
  18186. BoundingInfo.prototype.intersectsPoint = function (point) {
  18187. if (!this.boundingSphere.centerWorld) {
  18188. return false;
  18189. }
  18190. if (!this.boundingSphere.intersectsPoint(point)) {
  18191. return false;
  18192. }
  18193. if (!this.boundingBox.intersectsPoint(point)) {
  18194. return false;
  18195. }
  18196. return true;
  18197. };
  18198. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18199. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18200. return false;
  18201. }
  18202. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18203. return false;
  18204. }
  18205. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18206. return false;
  18207. }
  18208. if (!precise) {
  18209. return true;
  18210. }
  18211. var box0 = this.boundingBox;
  18212. var box1 = boundingInfo.boundingBox;
  18213. if (!axisOverlap(box0.directions[0], box0, box1))
  18214. return false;
  18215. if (!axisOverlap(box0.directions[1], box0, box1))
  18216. return false;
  18217. if (!axisOverlap(box0.directions[2], box0, box1))
  18218. return false;
  18219. if (!axisOverlap(box1.directions[0], box0, box1))
  18220. return false;
  18221. if (!axisOverlap(box1.directions[1], box0, box1))
  18222. return false;
  18223. if (!axisOverlap(box1.directions[2], box0, box1))
  18224. return false;
  18225. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18226. return false;
  18227. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18228. return false;
  18229. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18230. return false;
  18231. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18232. return false;
  18233. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18234. return false;
  18235. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18236. return false;
  18237. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18238. return false;
  18239. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18240. return false;
  18241. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18242. return false;
  18243. return true;
  18244. };
  18245. return BoundingInfo;
  18246. }());
  18247. BABYLON.BoundingInfo = BoundingInfo;
  18248. })(BABYLON || (BABYLON = {}));
  18249. //# sourceMappingURL=babylon.boundingInfo.js.map
  18250. var BABYLON;
  18251. (function (BABYLON) {
  18252. var TransformNode = /** @class */ (function (_super) {
  18253. __extends(TransformNode, _super);
  18254. function TransformNode(name, scene, isPure) {
  18255. if (scene === void 0) { scene = null; }
  18256. if (isPure === void 0) { isPure = true; }
  18257. var _this = _super.call(this, name, scene) || this;
  18258. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18259. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18260. _this._up = new BABYLON.Vector3(0, 1, 0);
  18261. _this._right = new BABYLON.Vector3(1, 0, 0);
  18262. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18263. // Properties
  18264. _this._rotation = BABYLON.Vector3.Zero();
  18265. _this._scaling = BABYLON.Vector3.One();
  18266. _this._isDirty = false;
  18267. /**
  18268. * Set the billboard mode. Default is 0.
  18269. *
  18270. * | Value | Type | Description |
  18271. * | --- | --- | --- |
  18272. * | 0 | BILLBOARDMODE_NONE | |
  18273. * | 1 | BILLBOARDMODE_X | |
  18274. * | 2 | BILLBOARDMODE_Y | |
  18275. * | 4 | BILLBOARDMODE_Z | |
  18276. * | 7 | BILLBOARDMODE_ALL | |
  18277. *
  18278. */
  18279. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18280. _this.scalingDeterminant = 1;
  18281. _this.infiniteDistance = false;
  18282. /**
  18283. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18284. * By default the system will update normals to compensate
  18285. */
  18286. _this.ignoreNonUniformScaling = false;
  18287. _this.position = BABYLON.Vector3.Zero();
  18288. _this._localWorld = BABYLON.Matrix.Zero();
  18289. _this._worldMatrix = BABYLON.Matrix.Zero();
  18290. _this._worldMatrixDeterminant = 0;
  18291. _this._absolutePosition = BABYLON.Vector3.Zero();
  18292. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18293. _this._postMultiplyPivotMatrix = false;
  18294. _this._isWorldMatrixFrozen = false;
  18295. /**
  18296. * An event triggered after the world matrix is updated
  18297. */
  18298. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18299. _this._nonUniformScaling = false;
  18300. if (isPure) {
  18301. _this.getScene().addTransformNode(_this);
  18302. }
  18303. return _this;
  18304. }
  18305. /**
  18306. * Gets a string idenfifying the name of the class
  18307. * @returns "TransformNode" string
  18308. */
  18309. TransformNode.prototype.getClassName = function () {
  18310. return "TransformNode";
  18311. };
  18312. Object.defineProperty(TransformNode.prototype, "rotation", {
  18313. /**
  18314. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18315. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18316. * Default : (0.0, 0.0, 0.0)
  18317. */
  18318. get: function () {
  18319. return this._rotation;
  18320. },
  18321. set: function (newRotation) {
  18322. this._rotation = newRotation;
  18323. },
  18324. enumerable: true,
  18325. configurable: true
  18326. });
  18327. Object.defineProperty(TransformNode.prototype, "scaling", {
  18328. /**
  18329. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18330. * Default : (1.0, 1.0, 1.0)
  18331. */
  18332. get: function () {
  18333. return this._scaling;
  18334. },
  18335. /**
  18336. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18337. * Default : (1.0, 1.0, 1.0)
  18338. */
  18339. set: function (newScaling) {
  18340. this._scaling = newScaling;
  18341. },
  18342. enumerable: true,
  18343. configurable: true
  18344. });
  18345. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18346. /**
  18347. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18348. * It's null by default.
  18349. * 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)
  18350. */
  18351. get: function () {
  18352. return this._rotationQuaternion;
  18353. },
  18354. set: function (quaternion) {
  18355. this._rotationQuaternion = quaternion;
  18356. //reset the rotation vector.
  18357. if (quaternion && this.rotation.length()) {
  18358. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18359. }
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. Object.defineProperty(TransformNode.prototype, "forward", {
  18365. /**
  18366. * The forward direction of that transform in world space.
  18367. */
  18368. get: function () {
  18369. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. Object.defineProperty(TransformNode.prototype, "up", {
  18375. /**
  18376. * The up direction of that transform in world space.
  18377. */
  18378. get: function () {
  18379. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. Object.defineProperty(TransformNode.prototype, "right", {
  18385. /**
  18386. * The right direction of that transform in world space.
  18387. */
  18388. get: function () {
  18389. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18390. },
  18391. enumerable: true,
  18392. configurable: true
  18393. });
  18394. /**
  18395. * Returns the latest update of the World matrix
  18396. * Returns a Matrix.
  18397. */
  18398. TransformNode.prototype.getWorldMatrix = function () {
  18399. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18400. this.computeWorldMatrix();
  18401. }
  18402. return this._worldMatrix;
  18403. };
  18404. /** @hidden */
  18405. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18406. return this._worldMatrixDeterminant;
  18407. };
  18408. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18409. /**
  18410. * Returns directly the latest state of the mesh World matrix.
  18411. * A Matrix is returned.
  18412. */
  18413. get: function () {
  18414. return this._worldMatrix;
  18415. },
  18416. enumerable: true,
  18417. configurable: true
  18418. });
  18419. /**
  18420. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18421. * Returns the TransformNode.
  18422. */
  18423. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18424. this._poseMatrix.copyFrom(matrix);
  18425. return this;
  18426. };
  18427. /**
  18428. * Returns the mesh Pose matrix.
  18429. * Returned object : Matrix
  18430. */
  18431. TransformNode.prototype.getPoseMatrix = function () {
  18432. return this._poseMatrix;
  18433. };
  18434. TransformNode.prototype._isSynchronized = function () {
  18435. if (this._isDirty) {
  18436. return false;
  18437. }
  18438. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18439. return false;
  18440. if (this._cache.pivotMatrixUpdated) {
  18441. return false;
  18442. }
  18443. if (this.infiniteDistance) {
  18444. return false;
  18445. }
  18446. if (!this._cache.position.equals(this.position))
  18447. return false;
  18448. if (this.rotationQuaternion) {
  18449. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18450. return false;
  18451. }
  18452. if (!this._cache.rotation.equals(this.rotation))
  18453. return false;
  18454. if (!this._cache.scaling.equals(this.scaling))
  18455. return false;
  18456. return true;
  18457. };
  18458. TransformNode.prototype._initCache = function () {
  18459. _super.prototype._initCache.call(this);
  18460. this._cache.localMatrixUpdated = false;
  18461. this._cache.position = BABYLON.Vector3.Zero();
  18462. this._cache.scaling = BABYLON.Vector3.Zero();
  18463. this._cache.rotation = BABYLON.Vector3.Zero();
  18464. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18465. this._cache.billboardMode = -1;
  18466. };
  18467. TransformNode.prototype.markAsDirty = function (property) {
  18468. if (property === "rotation") {
  18469. this.rotationQuaternion = null;
  18470. }
  18471. this._currentRenderId = Number.MAX_VALUE;
  18472. this._isDirty = true;
  18473. return this;
  18474. };
  18475. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18476. /**
  18477. * Returns the current mesh absolute position.
  18478. * Retuns a Vector3.
  18479. */
  18480. get: function () {
  18481. return this._absolutePosition;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. /**
  18487. * Sets a new matrix to apply before all other transformation
  18488. * @param matrix defines the transform matrix
  18489. * @returns the current TransformNode
  18490. */
  18491. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18492. return this.setPivotMatrix(matrix, false);
  18493. };
  18494. /**
  18495. * Sets a new pivot matrix to the current node
  18496. * @param matrix defines the new pivot matrix to use
  18497. * @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
  18498. * @returns the current TransformNode
  18499. */
  18500. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18501. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18502. this._pivotMatrix = matrix.clone();
  18503. this._cache.pivotMatrixUpdated = true;
  18504. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18505. if (this._postMultiplyPivotMatrix) {
  18506. if (!this._pivotMatrixInverse) {
  18507. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18508. }
  18509. else {
  18510. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18511. }
  18512. }
  18513. return this;
  18514. };
  18515. /**
  18516. * Returns the mesh pivot matrix.
  18517. * Default : Identity.
  18518. * A Matrix is returned.
  18519. */
  18520. TransformNode.prototype.getPivotMatrix = function () {
  18521. return this._pivotMatrix;
  18522. };
  18523. /**
  18524. * Prevents the World matrix to be computed any longer.
  18525. * Returns the TransformNode.
  18526. */
  18527. TransformNode.prototype.freezeWorldMatrix = function () {
  18528. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18529. this.computeWorldMatrix(true);
  18530. this._isWorldMatrixFrozen = true;
  18531. return this;
  18532. };
  18533. /**
  18534. * Allows back the World matrix computation.
  18535. * Returns the TransformNode.
  18536. */
  18537. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18538. this._isWorldMatrixFrozen = false;
  18539. this.computeWorldMatrix(true);
  18540. return this;
  18541. };
  18542. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18543. /**
  18544. * True if the World matrix has been frozen.
  18545. * Returns a boolean.
  18546. */
  18547. get: function () {
  18548. return this._isWorldMatrixFrozen;
  18549. },
  18550. enumerable: true,
  18551. configurable: true
  18552. });
  18553. /**
  18554. * Retuns the mesh absolute position in the World.
  18555. * Returns a Vector3.
  18556. */
  18557. TransformNode.prototype.getAbsolutePosition = function () {
  18558. this.computeWorldMatrix();
  18559. return this._absolutePosition;
  18560. };
  18561. /**
  18562. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18563. * Returns the TransformNode.
  18564. */
  18565. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18566. if (!absolutePosition) {
  18567. return this;
  18568. }
  18569. var absolutePositionX;
  18570. var absolutePositionY;
  18571. var absolutePositionZ;
  18572. if (absolutePosition.x === undefined) {
  18573. if (arguments.length < 3) {
  18574. return this;
  18575. }
  18576. absolutePositionX = arguments[0];
  18577. absolutePositionY = arguments[1];
  18578. absolutePositionZ = arguments[2];
  18579. }
  18580. else {
  18581. absolutePositionX = absolutePosition.x;
  18582. absolutePositionY = absolutePosition.y;
  18583. absolutePositionZ = absolutePosition.z;
  18584. }
  18585. if (this.parent) {
  18586. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18587. invertParentWorldMatrix.invert();
  18588. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18589. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18590. }
  18591. else {
  18592. this.position.x = absolutePositionX;
  18593. this.position.y = absolutePositionY;
  18594. this.position.z = absolutePositionZ;
  18595. }
  18596. return this;
  18597. };
  18598. /**
  18599. * Sets the mesh position in its local space.
  18600. * Returns the TransformNode.
  18601. */
  18602. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18603. this.computeWorldMatrix();
  18604. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18605. return this;
  18606. };
  18607. /**
  18608. * Returns the mesh position in the local space from the current World matrix values.
  18609. * Returns a new Vector3.
  18610. */
  18611. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18612. this.computeWorldMatrix();
  18613. var invLocalWorldMatrix = this._localWorld.clone();
  18614. invLocalWorldMatrix.invert();
  18615. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18616. };
  18617. /**
  18618. * Translates the mesh along the passed Vector3 in its local space.
  18619. * Returns the TransformNode.
  18620. */
  18621. TransformNode.prototype.locallyTranslate = function (vector3) {
  18622. this.computeWorldMatrix(true);
  18623. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18624. return this;
  18625. };
  18626. /**
  18627. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18628. * @param targetPoint the position (must be in same space as current mesh) to look at
  18629. * @param yawCor optional yaw (y-axis) correction in radians
  18630. * @param pitchCor optional pitch (x-axis) correction in radians
  18631. * @param rollCor optional roll (z-axis) correction in radians
  18632. * @param space the choosen space of the target
  18633. * @returns the TransformNode.
  18634. */
  18635. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18636. if (yawCor === void 0) { yawCor = 0; }
  18637. if (pitchCor === void 0) { pitchCor = 0; }
  18638. if (rollCor === void 0) { rollCor = 0; }
  18639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18640. var dv = TransformNode._lookAtVectorCache;
  18641. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18642. targetPoint.subtractToRef(pos, dv);
  18643. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18644. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18645. var pitch = Math.atan2(dv.y, len);
  18646. if (this.rotationQuaternion) {
  18647. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18648. }
  18649. else {
  18650. this.rotation.x = pitch + pitchCor;
  18651. this.rotation.y = yaw + yawCor;
  18652. this.rotation.z = rollCor;
  18653. }
  18654. return this;
  18655. };
  18656. /**
  18657. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18658. * This Vector3 is expressed in the World space.
  18659. */
  18660. TransformNode.prototype.getDirection = function (localAxis) {
  18661. var result = BABYLON.Vector3.Zero();
  18662. this.getDirectionToRef(localAxis, result);
  18663. return result;
  18664. };
  18665. /**
  18666. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18667. * localAxis is expressed in the mesh local space.
  18668. * result is computed in the Wordl space from the mesh World matrix.
  18669. * Returns the TransformNode.
  18670. */
  18671. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18672. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18673. return this;
  18674. };
  18675. /**
  18676. * Sets a new pivot point to the current node
  18677. * @param point defines the new pivot point to use
  18678. * @param space defines if the point is in world or local space (local by default)
  18679. * @returns the current TransformNode
  18680. */
  18681. TransformNode.prototype.setPivotPoint = function (point, space) {
  18682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18683. if (this.getScene().getRenderId() == 0) {
  18684. this.computeWorldMatrix(true);
  18685. }
  18686. var wm = this.getWorldMatrix();
  18687. if (space == BABYLON.Space.WORLD) {
  18688. var tmat = BABYLON.Tmp.Matrix[0];
  18689. wm.invertToRef(tmat);
  18690. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18691. }
  18692. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18693. };
  18694. /**
  18695. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18696. */
  18697. TransformNode.prototype.getPivotPoint = function () {
  18698. var point = BABYLON.Vector3.Zero();
  18699. this.getPivotPointToRef(point);
  18700. return point;
  18701. };
  18702. /**
  18703. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18704. * Returns the TransformNode.
  18705. */
  18706. TransformNode.prototype.getPivotPointToRef = function (result) {
  18707. result.x = -this._pivotMatrix.m[12];
  18708. result.y = -this._pivotMatrix.m[13];
  18709. result.z = -this._pivotMatrix.m[14];
  18710. return this;
  18711. };
  18712. /**
  18713. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18714. */
  18715. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18716. var point = BABYLON.Vector3.Zero();
  18717. this.getAbsolutePivotPointToRef(point);
  18718. return point;
  18719. };
  18720. /**
  18721. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18722. * Returns the TransformNode.
  18723. */
  18724. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18725. result.x = this._pivotMatrix.m[12];
  18726. result.y = this._pivotMatrix.m[13];
  18727. result.z = this._pivotMatrix.m[14];
  18728. this.getPivotPointToRef(result);
  18729. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18730. return this;
  18731. };
  18732. /**
  18733. * Defines the passed node as the parent of the current node.
  18734. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18735. * Returns the TransformNode.
  18736. */
  18737. TransformNode.prototype.setParent = function (node) {
  18738. if (!node && !this.parent) {
  18739. return this;
  18740. }
  18741. if (!node) {
  18742. var rotation = BABYLON.Tmp.Quaternion[0];
  18743. var position = BABYLON.Tmp.Vector3[0];
  18744. var scale = BABYLON.Tmp.Vector3[1];
  18745. if (this.parent && this.parent.computeWorldMatrix) {
  18746. this.parent.computeWorldMatrix(true);
  18747. }
  18748. this.computeWorldMatrix(true);
  18749. this.getWorldMatrix().decompose(scale, rotation, position);
  18750. if (this.rotationQuaternion) {
  18751. this.rotationQuaternion.copyFrom(rotation);
  18752. }
  18753. else {
  18754. rotation.toEulerAnglesToRef(this.rotation);
  18755. }
  18756. this.scaling.x = scale.x;
  18757. this.scaling.y = scale.y;
  18758. this.scaling.z = scale.z;
  18759. this.position.x = position.x;
  18760. this.position.y = position.y;
  18761. this.position.z = position.z;
  18762. }
  18763. else {
  18764. var rotation = BABYLON.Tmp.Quaternion[0];
  18765. var position = BABYLON.Tmp.Vector3[0];
  18766. var scale = BABYLON.Tmp.Vector3[1];
  18767. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18768. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18769. this.computeWorldMatrix(true);
  18770. node.computeWorldMatrix(true);
  18771. node.getWorldMatrix().invertToRef(invParentMatrix);
  18772. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18773. diffMatrix.decompose(scale, rotation, position);
  18774. if (this.rotationQuaternion) {
  18775. this.rotationQuaternion.copyFrom(rotation);
  18776. }
  18777. else {
  18778. rotation.toEulerAnglesToRef(this.rotation);
  18779. }
  18780. this.position.x = position.x;
  18781. this.position.y = position.y;
  18782. this.position.z = position.z;
  18783. this.scaling.x = scale.x;
  18784. this.scaling.y = scale.y;
  18785. this.scaling.z = scale.z;
  18786. }
  18787. this.parent = node;
  18788. return this;
  18789. };
  18790. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18791. get: function () {
  18792. return this._nonUniformScaling;
  18793. },
  18794. enumerable: true,
  18795. configurable: true
  18796. });
  18797. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18798. if (this._nonUniformScaling === value) {
  18799. return false;
  18800. }
  18801. this._nonUniformScaling = value;
  18802. return true;
  18803. };
  18804. /**
  18805. * Attach the current TransformNode to another TransformNode associated with a bone
  18806. * @param bone Bone affecting the TransformNode
  18807. * @param affectedTransformNode TransformNode associated with the bone
  18808. */
  18809. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18810. this._transformToBoneReferal = affectedTransformNode;
  18811. this.parent = bone;
  18812. if (bone.getWorldMatrix().determinant() < 0) {
  18813. this.scalingDeterminant *= -1;
  18814. }
  18815. return this;
  18816. };
  18817. TransformNode.prototype.detachFromBone = function () {
  18818. if (!this.parent) {
  18819. return this;
  18820. }
  18821. if (this.parent.getWorldMatrix().determinant() < 0) {
  18822. this.scalingDeterminant *= -1;
  18823. }
  18824. this._transformToBoneReferal = null;
  18825. this.parent = null;
  18826. return this;
  18827. };
  18828. /**
  18829. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18830. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18831. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18832. * The passed axis is also normalized.
  18833. * Returns the TransformNode.
  18834. */
  18835. TransformNode.prototype.rotate = function (axis, amount, space) {
  18836. axis.normalize();
  18837. if (!this.rotationQuaternion) {
  18838. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18839. this.rotation = BABYLON.Vector3.Zero();
  18840. }
  18841. var rotationQuaternion;
  18842. if (!space || space === BABYLON.Space.LOCAL) {
  18843. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18844. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18845. }
  18846. else {
  18847. if (this.parent) {
  18848. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18849. invertParentWorldMatrix.invert();
  18850. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18851. }
  18852. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18853. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18854. }
  18855. return this;
  18856. };
  18857. /**
  18858. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18859. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18860. * The passed axis is also normalized.
  18861. * Returns the TransformNode.
  18862. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18863. */
  18864. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18865. axis.normalize();
  18866. if (!this.rotationQuaternion) {
  18867. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18868. this.rotation.copyFromFloats(0, 0, 0);
  18869. }
  18870. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18871. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18872. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18873. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18874. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18875. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18876. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18877. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18878. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18879. return this;
  18880. };
  18881. /**
  18882. * Translates the mesh along the axis vector for the passed distance in the given space.
  18883. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18884. * Returns the TransformNode.
  18885. */
  18886. TransformNode.prototype.translate = function (axis, distance, space) {
  18887. var displacementVector = axis.scale(distance);
  18888. if (!space || space === BABYLON.Space.LOCAL) {
  18889. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18890. this.setPositionWithLocalVector(tempV3);
  18891. }
  18892. else {
  18893. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18894. }
  18895. return this;
  18896. };
  18897. /**
  18898. * Adds a rotation step to the mesh current rotation.
  18899. * x, y, z are Euler angles expressed in radians.
  18900. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18901. * This means this rotation is made in the mesh local space only.
  18902. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18903. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18904. * ```javascript
  18905. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18906. * ```
  18907. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18908. * 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.
  18909. * Returns the TransformNode.
  18910. */
  18911. TransformNode.prototype.addRotation = function (x, y, z) {
  18912. var rotationQuaternion;
  18913. if (this.rotationQuaternion) {
  18914. rotationQuaternion = this.rotationQuaternion;
  18915. }
  18916. else {
  18917. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18918. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18919. }
  18920. var accumulation = BABYLON.Tmp.Quaternion[0];
  18921. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18922. rotationQuaternion.multiplyInPlace(accumulation);
  18923. if (!this.rotationQuaternion) {
  18924. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18925. }
  18926. return this;
  18927. };
  18928. /**
  18929. * Computes the mesh World matrix and returns it.
  18930. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18931. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18932. * If the parameter `force`is set to `true`, the actual computation is done.
  18933. * Returns the mesh World Matrix.
  18934. */
  18935. TransformNode.prototype.computeWorldMatrix = function (force) {
  18936. if (this._isWorldMatrixFrozen) {
  18937. return this._worldMatrix;
  18938. }
  18939. if (!force && this.isSynchronized(true)) {
  18940. this._currentRenderId = this.getScene().getRenderId();
  18941. return this._worldMatrix;
  18942. }
  18943. this._cache.position.copyFrom(this.position);
  18944. this._cache.scaling.copyFrom(this.scaling);
  18945. this._cache.pivotMatrixUpdated = false;
  18946. this._cache.billboardMode = this.billboardMode;
  18947. this._currentRenderId = this.getScene().getRenderId();
  18948. this._childRenderId = this.getScene().getRenderId();
  18949. this._isDirty = false;
  18950. // Scaling
  18951. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18952. // Rotation
  18953. //rotate, if quaternion is set and rotation was used
  18954. if (this.rotationQuaternion) {
  18955. var len = this.rotation.length();
  18956. if (len) {
  18957. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18958. this.rotation.copyFromFloats(0, 0, 0);
  18959. }
  18960. }
  18961. if (this.rotationQuaternion) {
  18962. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18963. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18964. }
  18965. else {
  18966. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18967. this._cache.rotation.copyFrom(this.rotation);
  18968. }
  18969. // Translation
  18970. var camera = this.getScene().activeCamera;
  18971. if (this.infiniteDistance && !this.parent && camera) {
  18972. var cameraWorldMatrix = camera.getWorldMatrix();
  18973. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18974. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18975. }
  18976. else {
  18977. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18978. }
  18979. // Composing transformations
  18980. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18981. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18982. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18983. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18984. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18985. // Need to decompose each rotation here
  18986. var currentPosition = BABYLON.Tmp.Vector3[3];
  18987. if (this.parent && this.parent.getWorldMatrix) {
  18988. if (this._transformToBoneReferal) {
  18989. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18990. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18991. }
  18992. else {
  18993. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18994. }
  18995. }
  18996. else {
  18997. currentPosition.copyFrom(this.position);
  18998. }
  18999. currentPosition.subtractInPlace(camera.globalPosition);
  19000. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19001. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19002. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19003. }
  19004. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19005. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19006. }
  19007. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19008. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19009. }
  19010. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19011. }
  19012. else {
  19013. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19014. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19015. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19016. }
  19017. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19018. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19019. }
  19020. // Post multiply inverse of pivotMatrix
  19021. if (this._postMultiplyPivotMatrix) {
  19022. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19023. }
  19024. // Local world
  19025. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19026. // Parent
  19027. if (this.parent && this.parent.getWorldMatrix) {
  19028. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19029. if (this._transformToBoneReferal) {
  19030. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19031. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19032. }
  19033. else {
  19034. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19035. }
  19036. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19037. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19038. this._worldMatrix.copyFrom(this._localWorld);
  19039. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19040. }
  19041. else {
  19042. if (this._transformToBoneReferal) {
  19043. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19044. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19045. }
  19046. else {
  19047. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19048. }
  19049. }
  19050. this._markSyncedWithParent();
  19051. }
  19052. else {
  19053. this._worldMatrix.copyFrom(this._localWorld);
  19054. }
  19055. // Normal matrix
  19056. if (!this.ignoreNonUniformScaling) {
  19057. if (this.scaling.isNonUniform) {
  19058. this._updateNonUniformScalingState(true);
  19059. }
  19060. else if (this.parent && this.parent._nonUniformScaling) {
  19061. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19062. }
  19063. else {
  19064. this._updateNonUniformScalingState(false);
  19065. }
  19066. }
  19067. else {
  19068. this._updateNonUniformScalingState(false);
  19069. }
  19070. this._afterComputeWorldMatrix();
  19071. // Absolute position
  19072. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19073. // Callbacks
  19074. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19075. if (!this._poseMatrix) {
  19076. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19077. }
  19078. // Cache the determinant
  19079. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19080. return this._worldMatrix;
  19081. };
  19082. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19083. };
  19084. /**
  19085. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19086. * @param func: callback function to add
  19087. *
  19088. * Returns the TransformNode.
  19089. */
  19090. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19091. this.onAfterWorldMatrixUpdateObservable.add(func);
  19092. return this;
  19093. };
  19094. /**
  19095. * Removes a registered callback function.
  19096. * Returns the TransformNode.
  19097. */
  19098. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19099. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19100. return this;
  19101. };
  19102. /**
  19103. * Clone the current transform node
  19104. * Returns the new transform node
  19105. * @param name Name of the new clone
  19106. * @param newParent New parent for the clone
  19107. * @param doNotCloneChildren Do not clone children hierarchy
  19108. */
  19109. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19110. var _this = this;
  19111. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19112. result.name = name;
  19113. result.id = name;
  19114. if (newParent) {
  19115. result.parent = newParent;
  19116. }
  19117. if (!doNotCloneChildren) {
  19118. // Children
  19119. var directDescendants = this.getDescendants(true);
  19120. for (var index = 0; index < directDescendants.length; index++) {
  19121. var child = directDescendants[index];
  19122. if (child.clone) {
  19123. child.clone(name + "." + child.name, result);
  19124. }
  19125. }
  19126. }
  19127. return result;
  19128. };
  19129. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19130. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19131. serializationObject.type = this.getClassName();
  19132. // Parent
  19133. if (this.parent) {
  19134. serializationObject.parentId = this.parent.id;
  19135. }
  19136. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19137. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19138. }
  19139. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19140. serializationObject.isEnabled = this.isEnabled();
  19141. // Parent
  19142. if (this.parent) {
  19143. serializationObject.parentId = this.parent.id;
  19144. }
  19145. return serializationObject;
  19146. };
  19147. // Statics
  19148. /**
  19149. * Returns a new TransformNode object parsed from the source provided.
  19150. * The parameter `parsedMesh` is the source.
  19151. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19152. */
  19153. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19154. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19155. if (BABYLON.Tags) {
  19156. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19157. }
  19158. if (parsedTransformNode.localMatrix) {
  19159. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19160. }
  19161. else if (parsedTransformNode.pivotMatrix) {
  19162. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19163. }
  19164. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19165. // Parent
  19166. if (parsedTransformNode.parentId) {
  19167. transformNode._waitingParentId = parsedTransformNode.parentId;
  19168. }
  19169. return transformNode;
  19170. };
  19171. /**
  19172. * Releases resources associated with this transform node.
  19173. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19174. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19175. */
  19176. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19177. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19178. // Animations
  19179. this.getScene().stopAnimation(this);
  19180. // Remove from scene
  19181. this.getScene().removeTransformNode(this);
  19182. this.onAfterWorldMatrixUpdateObservable.clear();
  19183. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19184. };
  19185. // Statics
  19186. TransformNode.BILLBOARDMODE_NONE = 0;
  19187. TransformNode.BILLBOARDMODE_X = 1;
  19188. TransformNode.BILLBOARDMODE_Y = 2;
  19189. TransformNode.BILLBOARDMODE_Z = 4;
  19190. TransformNode.BILLBOARDMODE_ALL = 7;
  19191. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19192. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19193. __decorate([
  19194. BABYLON.serializeAsVector3()
  19195. ], TransformNode.prototype, "_rotation", void 0);
  19196. __decorate([
  19197. BABYLON.serializeAsQuaternion()
  19198. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19199. __decorate([
  19200. BABYLON.serializeAsVector3()
  19201. ], TransformNode.prototype, "_scaling", void 0);
  19202. __decorate([
  19203. BABYLON.serialize()
  19204. ], TransformNode.prototype, "billboardMode", void 0);
  19205. __decorate([
  19206. BABYLON.serialize()
  19207. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19208. __decorate([
  19209. BABYLON.serialize()
  19210. ], TransformNode.prototype, "infiniteDistance", void 0);
  19211. __decorate([
  19212. BABYLON.serialize()
  19213. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19214. __decorate([
  19215. BABYLON.serializeAsVector3()
  19216. ], TransformNode.prototype, "position", void 0);
  19217. return TransformNode;
  19218. }(BABYLON.Node));
  19219. BABYLON.TransformNode = TransformNode;
  19220. })(BABYLON || (BABYLON = {}));
  19221. //# sourceMappingURL=babylon.transformNode.js.map
  19222. var BABYLON;
  19223. (function (BABYLON) {
  19224. /**
  19225. * Class used to store all common mesh properties
  19226. */
  19227. var AbstractMesh = /** @class */ (function (_super) {
  19228. __extends(AbstractMesh, _super);
  19229. // Constructor
  19230. /**
  19231. * Creates a new AbstractMesh
  19232. * @param name defines the name of the mesh
  19233. * @param scene defines the hosting scene
  19234. */
  19235. function AbstractMesh(name, scene) {
  19236. if (scene === void 0) { scene = null; }
  19237. var _this = _super.call(this, name, scene, false) || this;
  19238. _this._facetNb = 0; // facet number
  19239. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19240. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19241. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19242. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19243. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19244. _this._subDiv = {
  19245. max: 1,
  19246. X: 1,
  19247. Y: 1,
  19248. Z: 1
  19249. };
  19250. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19251. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19252. // Events
  19253. /**
  19254. * An event triggered when this mesh collides with another one
  19255. */
  19256. _this.onCollideObservable = new BABYLON.Observable();
  19257. /**
  19258. * An event triggered when the collision's position changes
  19259. */
  19260. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19261. /**
  19262. * An event triggered when material is changed
  19263. */
  19264. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19265. // Properties
  19266. /**
  19267. * Gets or sets the orientation for POV movement & rotation
  19268. */
  19269. _this.definedFacingForward = true;
  19270. /**
  19271. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19272. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19273. * * 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.
  19274. * @see http://doc.babylonjs.com/features/occlusionquery
  19275. */
  19276. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19277. /**
  19278. * 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:
  19279. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19280. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19281. * * 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.
  19282. * @see http://doc.babylonjs.com/features/occlusionquery
  19283. */
  19284. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19285. /**
  19286. * 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.
  19287. * The default value is -1 which means don't break the query and wait till the result
  19288. * @see http://doc.babylonjs.com/features/occlusionquery
  19289. */
  19290. _this.occlusionRetryCount = -1;
  19291. /** @hidden */
  19292. _this._occlusionInternalRetryCounter = 0;
  19293. /** @hidden */
  19294. _this._isOccluded = false;
  19295. /** @hidden */
  19296. _this._isOcclusionQueryInProgress = false;
  19297. _this._visibility = 1.0;
  19298. /** Gets or sets the alpha index used to sort transparent meshes
  19299. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19300. */
  19301. _this.alphaIndex = Number.MAX_VALUE;
  19302. /**
  19303. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19304. */
  19305. _this.isVisible = true;
  19306. /**
  19307. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19308. */
  19309. _this.isPickable = true;
  19310. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19311. _this.showSubMeshesBoundingBox = false;
  19312. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19313. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19314. */
  19315. _this.isBlocker = false;
  19316. /**
  19317. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19318. */
  19319. _this.enablePointerMoveEvents = false;
  19320. /**
  19321. * Specifies the rendering group id for this mesh (0 by default)
  19322. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19323. */
  19324. _this.renderingGroupId = 0;
  19325. _this._receiveShadows = false;
  19326. /**
  19327. * Gets or sets a boolean indicating if the outline must be rendered as well
  19328. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19329. */
  19330. _this.renderOutline = false;
  19331. /** Defines color to use when rendering outline */
  19332. _this.outlineColor = BABYLON.Color3.Red();
  19333. /** Define width to use when rendering outline */
  19334. _this.outlineWidth = 0.02;
  19335. /**
  19336. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19337. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19338. */
  19339. _this.renderOverlay = false;
  19340. /** Defines color to use when rendering overlay */
  19341. _this.overlayColor = BABYLON.Color3.Red();
  19342. /** Defines alpha to use when rendering overlay */
  19343. _this.overlayAlpha = 0.5;
  19344. _this._hasVertexAlpha = false;
  19345. _this._useVertexColors = true;
  19346. _this._computeBonesUsingShaders = true;
  19347. _this._numBoneInfluencers = 4;
  19348. _this._applyFog = true;
  19349. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19350. _this.useOctreeForRenderingSelection = true;
  19351. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19352. _this.useOctreeForPicking = true;
  19353. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19354. _this.useOctreeForCollisions = true;
  19355. _this._layerMask = 0x0FFFFFFF;
  19356. /**
  19357. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19358. */
  19359. _this.alwaysSelectAsActiveMesh = false;
  19360. /**
  19361. * Gets or sets the current action manager
  19362. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19363. */
  19364. _this.actionManager = null;
  19365. /**
  19366. * Gets or sets impostor used for physic simulation
  19367. * @see http://doc.babylonjs.com/features/physics_engine
  19368. */
  19369. _this.physicsImpostor = null;
  19370. // Collisions
  19371. _this._checkCollisions = false;
  19372. _this._collisionMask = -1;
  19373. _this._collisionGroup = -1;
  19374. /**
  19375. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19376. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19377. */
  19378. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19379. /**
  19380. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19381. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19382. */
  19383. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19384. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19385. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19386. // Edges
  19387. /**
  19388. * Defines edge width used when edgesRenderer is enabled
  19389. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19390. */
  19391. _this.edgesWidth = 1;
  19392. /**
  19393. * Defines edge color used when edgesRenderer is enabled
  19394. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19395. */
  19396. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19397. // Cache
  19398. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19399. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19400. /** @hidden */
  19401. _this._renderId = 0;
  19402. /** @hidden */
  19403. _this._intersectionsInProgress = new Array();
  19404. /** @hidden */
  19405. _this._unIndexed = false;
  19406. /** @hidden */
  19407. _this._lightSources = new Array();
  19408. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19409. if (collidedMesh === void 0) { collidedMesh = null; }
  19410. //TODO move this to the collision coordinator!
  19411. if (_this.getScene().workerCollisions)
  19412. newPosition.multiplyInPlace(_this._collider._radius);
  19413. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19414. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19415. _this.position.addInPlace(_this._diffPositionForCollisions);
  19416. }
  19417. if (collidedMesh) {
  19418. _this.onCollideObservable.notifyObservers(collidedMesh);
  19419. }
  19420. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19421. };
  19422. _this.getScene().addMesh(_this);
  19423. _this._resyncLightSources();
  19424. return _this;
  19425. }
  19426. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19427. /**
  19428. * No billboard
  19429. */
  19430. get: function () {
  19431. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19432. },
  19433. enumerable: true,
  19434. configurable: true
  19435. });
  19436. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19437. /** Billboard on X axis */
  19438. get: function () {
  19439. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19440. },
  19441. enumerable: true,
  19442. configurable: true
  19443. });
  19444. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19445. /** Billboard on Y axis */
  19446. get: function () {
  19447. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19448. },
  19449. enumerable: true,
  19450. configurable: true
  19451. });
  19452. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19453. /** Billboard on Z axis */
  19454. get: function () {
  19455. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19456. },
  19457. enumerable: true,
  19458. configurable: true
  19459. });
  19460. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19461. /** Billboard on all axes */
  19462. get: function () {
  19463. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19469. /**
  19470. * Gets the number of facets in the mesh
  19471. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19472. */
  19473. get: function () {
  19474. return this._facetNb;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19480. /**
  19481. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19482. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19483. */
  19484. get: function () {
  19485. return this._partitioningSubdivisions;
  19486. },
  19487. set: function (nb) {
  19488. this._partitioningSubdivisions = nb;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19494. /**
  19495. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19496. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19497. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19498. */
  19499. get: function () {
  19500. return this._partitioningBBoxRatio;
  19501. },
  19502. set: function (ratio) {
  19503. this._partitioningBBoxRatio = ratio;
  19504. },
  19505. enumerable: true,
  19506. configurable: true
  19507. });
  19508. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19509. /**
  19510. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19511. * Works only for updatable meshes.
  19512. * Doesn't work with multi-materials
  19513. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19514. */
  19515. get: function () {
  19516. return this._facetDepthSort;
  19517. },
  19518. set: function (sort) {
  19519. this._facetDepthSort = sort;
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19525. /**
  19526. * The location (Vector3) where the facet depth sort must be computed from.
  19527. * By default, the active camera position.
  19528. * Used only when facet depth sort is enabled
  19529. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19530. */
  19531. get: function () {
  19532. return this._facetDepthSortFrom;
  19533. },
  19534. set: function (location) {
  19535. this._facetDepthSortFrom = location;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19541. /**
  19542. * gets a boolean indicating if facetData is enabled
  19543. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19544. */
  19545. get: function () {
  19546. return this._facetDataEnabled;
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. /** @hidden */
  19552. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19553. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19554. return false;
  19555. }
  19556. this._markSubMeshesAsMiscDirty();
  19557. return true;
  19558. };
  19559. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19560. /** Set a function to call when this mesh collides with another one */
  19561. set: function (callback) {
  19562. if (this._onCollideObserver) {
  19563. this.onCollideObservable.remove(this._onCollideObserver);
  19564. }
  19565. this._onCollideObserver = this.onCollideObservable.add(callback);
  19566. },
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19571. /** Set a function to call when the collision's position changes */
  19572. set: function (callback) {
  19573. if (this._onCollisionPositionChangeObserver) {
  19574. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19575. }
  19576. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19577. },
  19578. enumerable: true,
  19579. configurable: true
  19580. });
  19581. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19582. /**
  19583. * 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
  19584. * @see http://doc.babylonjs.com/features/occlusionquery
  19585. */
  19586. get: function () {
  19587. return this._isOccluded;
  19588. },
  19589. set: function (value) {
  19590. this._isOccluded = value;
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19596. /**
  19597. * Flag to check the progress status of the query
  19598. * @see http://doc.babylonjs.com/features/occlusionquery
  19599. */
  19600. get: function () {
  19601. return this._isOcclusionQueryInProgress;
  19602. },
  19603. enumerable: true,
  19604. configurable: true
  19605. });
  19606. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19607. /**
  19608. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19609. */
  19610. get: function () {
  19611. return this._visibility;
  19612. },
  19613. /**
  19614. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19615. */
  19616. set: function (value) {
  19617. if (this._visibility === value) {
  19618. return;
  19619. }
  19620. this._visibility = value;
  19621. this._markSubMeshesAsMiscDirty();
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. Object.defineProperty(AbstractMesh.prototype, "material", {
  19627. /** Gets or sets current material */
  19628. get: function () {
  19629. return this._material;
  19630. },
  19631. set: function (value) {
  19632. if (this._material === value) {
  19633. return;
  19634. }
  19635. this._material = value;
  19636. if (this.onMaterialChangedObservable.hasObservers) {
  19637. this.onMaterialChangedObservable.notifyObservers(this);
  19638. }
  19639. if (!this.subMeshes) {
  19640. return;
  19641. }
  19642. this._unBindEffect();
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19648. /**
  19649. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19650. * @see http://doc.babylonjs.com/babylon101/shadows
  19651. */
  19652. get: function () {
  19653. return this._receiveShadows;
  19654. },
  19655. set: function (value) {
  19656. if (this._receiveShadows === value) {
  19657. return;
  19658. }
  19659. this._receiveShadows = value;
  19660. this._markSubMeshesAsLightDirty();
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19666. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19667. get: function () {
  19668. return this._hasVertexAlpha;
  19669. },
  19670. set: function (value) {
  19671. if (this._hasVertexAlpha === value) {
  19672. return;
  19673. }
  19674. this._hasVertexAlpha = value;
  19675. this._markSubMeshesAsAttributesDirty();
  19676. this._markSubMeshesAsMiscDirty();
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19682. /** 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) */
  19683. get: function () {
  19684. return this._useVertexColors;
  19685. },
  19686. set: function (value) {
  19687. if (this._useVertexColors === value) {
  19688. return;
  19689. }
  19690. this._useVertexColors = value;
  19691. this._markSubMeshesAsAttributesDirty();
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19697. /**
  19698. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19699. */
  19700. get: function () {
  19701. return this._computeBonesUsingShaders;
  19702. },
  19703. set: function (value) {
  19704. if (this._computeBonesUsingShaders === value) {
  19705. return;
  19706. }
  19707. this._computeBonesUsingShaders = value;
  19708. this._markSubMeshesAsAttributesDirty();
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19714. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19715. get: function () {
  19716. return this._numBoneInfluencers;
  19717. },
  19718. set: function (value) {
  19719. if (this._numBoneInfluencers === value) {
  19720. return;
  19721. }
  19722. this._numBoneInfluencers = value;
  19723. this._markSubMeshesAsAttributesDirty();
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19729. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19730. get: function () {
  19731. return this._applyFog;
  19732. },
  19733. set: function (value) {
  19734. if (this._applyFog === value) {
  19735. return;
  19736. }
  19737. this._applyFog = value;
  19738. this._markSubMeshesAsMiscDirty();
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19744. /**
  19745. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19746. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19747. */
  19748. get: function () {
  19749. return this._layerMask;
  19750. },
  19751. set: function (value) {
  19752. if (value === this._layerMask) {
  19753. return;
  19754. }
  19755. this._layerMask = value;
  19756. this._resyncLightSources();
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19762. /**
  19763. * Gets or sets a collision mask used to mask collisions (default is -1).
  19764. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19765. */
  19766. get: function () {
  19767. return this._collisionMask;
  19768. },
  19769. set: function (mask) {
  19770. this._collisionMask = !isNaN(mask) ? mask : -1;
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19776. /**
  19777. * Gets or sets the current collision group mask (-1 by default).
  19778. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19779. */
  19780. get: function () {
  19781. return this._collisionGroup;
  19782. },
  19783. set: function (mask) {
  19784. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19790. /** @hidden */
  19791. get: function () {
  19792. return null;
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19798. get: function () {
  19799. return this._skeleton;
  19800. },
  19801. /**
  19802. * Gets or sets a skeleton to apply skining transformations
  19803. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19804. */
  19805. set: function (value) {
  19806. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19807. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19808. }
  19809. if (value && value.needInitialSkinMatrix) {
  19810. value._registerMeshWithPoseMatrix(this);
  19811. }
  19812. this._skeleton = value;
  19813. if (!this._skeleton) {
  19814. this._bonesTransformMatrices = null;
  19815. }
  19816. this._markSubMeshesAsAttributesDirty();
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. /**
  19822. * Returns the string "AbstractMesh"
  19823. * @returns "AbstractMesh"
  19824. */
  19825. AbstractMesh.prototype.getClassName = function () {
  19826. return "AbstractMesh";
  19827. };
  19828. /**
  19829. * Gets a string representation of the current mesh
  19830. * @param fullDetails defines a boolean indicating if full details must be included
  19831. * @returns a string representation of the current mesh
  19832. */
  19833. AbstractMesh.prototype.toString = function (fullDetails) {
  19834. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19835. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19836. if (this._skeleton) {
  19837. ret += ", skeleton: " + this._skeleton.name;
  19838. }
  19839. if (fullDetails) {
  19840. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19841. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19842. }
  19843. return ret;
  19844. };
  19845. /** @hidden */
  19846. AbstractMesh.prototype._rebuild = function () {
  19847. if (this._occlusionQuery) {
  19848. this._occlusionQuery = null;
  19849. }
  19850. if (this._edgesRenderer) {
  19851. this._edgesRenderer._rebuild();
  19852. }
  19853. if (!this.subMeshes) {
  19854. return;
  19855. }
  19856. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19857. var subMesh = _a[_i];
  19858. subMesh._rebuild();
  19859. }
  19860. };
  19861. /** @hidden */
  19862. AbstractMesh.prototype._resyncLightSources = function () {
  19863. this._lightSources.length = 0;
  19864. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19865. var light = _a[_i];
  19866. if (!light.isEnabled()) {
  19867. continue;
  19868. }
  19869. if (light.canAffectMesh(this)) {
  19870. this._lightSources.push(light);
  19871. }
  19872. }
  19873. this._markSubMeshesAsLightDirty();
  19874. };
  19875. /** @hidden */
  19876. AbstractMesh.prototype._resyncLighSource = function (light) {
  19877. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19878. var index = this._lightSources.indexOf(light);
  19879. if (index === -1) {
  19880. if (!isIn) {
  19881. return;
  19882. }
  19883. this._lightSources.push(light);
  19884. }
  19885. else {
  19886. if (isIn) {
  19887. return;
  19888. }
  19889. this._lightSources.splice(index, 1);
  19890. }
  19891. this._markSubMeshesAsLightDirty();
  19892. };
  19893. /** @hidden */
  19894. AbstractMesh.prototype._unBindEffect = function () {
  19895. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19896. var subMesh = _a[_i];
  19897. subMesh.setEffect(null);
  19898. }
  19899. };
  19900. /** @hidden */
  19901. AbstractMesh.prototype._removeLightSource = function (light) {
  19902. var index = this._lightSources.indexOf(light);
  19903. if (index === -1) {
  19904. return;
  19905. }
  19906. this._lightSources.splice(index, 1);
  19907. this._markSubMeshesAsLightDirty();
  19908. };
  19909. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19910. if (!this.subMeshes) {
  19911. return;
  19912. }
  19913. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19914. var subMesh = _a[_i];
  19915. if (subMesh._materialDefines) {
  19916. func(subMesh._materialDefines);
  19917. }
  19918. }
  19919. };
  19920. /** @hidden */
  19921. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19922. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19923. };
  19924. /** @hidden */
  19925. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19926. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19927. };
  19928. /** @hidden */
  19929. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19930. if (!this.subMeshes) {
  19931. return;
  19932. }
  19933. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19934. var subMesh = _a[_i];
  19935. var material = subMesh.getMaterial();
  19936. if (material) {
  19937. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19938. }
  19939. }
  19940. };
  19941. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19942. /**
  19943. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19944. */
  19945. get: function () {
  19946. return this._scaling;
  19947. },
  19948. set: function (newScaling) {
  19949. this._scaling = newScaling;
  19950. if (this.physicsImpostor) {
  19951. this.physicsImpostor.forceUpdate();
  19952. }
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. // Methods
  19958. /**
  19959. * Disables the mesh edge rendering mode
  19960. * @returns the currentAbstractMesh
  19961. */
  19962. AbstractMesh.prototype.disableEdgesRendering = function () {
  19963. if (this._edgesRenderer) {
  19964. this._edgesRenderer.dispose();
  19965. this._edgesRenderer = null;
  19966. }
  19967. return this;
  19968. };
  19969. /**
  19970. * Enables the edge rendering mode on the mesh.
  19971. * This mode makes the mesh edges visible
  19972. * @param epsilon defines the maximal distance between two angles to detect a face
  19973. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19974. * @returns the currentAbstractMesh
  19975. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19976. */
  19977. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19978. if (epsilon === void 0) { epsilon = 0.95; }
  19979. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19980. this.disableEdgesRendering();
  19981. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19982. return this;
  19983. };
  19984. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  19985. /**
  19986. * Gets the edgesRenderer associated with the mesh
  19987. */
  19988. get: function () {
  19989. return this._edgesRenderer;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19995. /**
  19996. * Returns true if the mesh is blocked. Implemented by child classes
  19997. */
  19998. get: function () {
  19999. return false;
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. /**
  20005. * Returns the mesh itself by default. Implemented by child classes
  20006. * @param camera defines the camera to use to pick the right LOD level
  20007. * @returns the currentAbstractMesh
  20008. */
  20009. AbstractMesh.prototype.getLOD = function (camera) {
  20010. return this;
  20011. };
  20012. /**
  20013. * Returns 0 by default. Implemented by child classes
  20014. * @returns an integer
  20015. */
  20016. AbstractMesh.prototype.getTotalVertices = function () {
  20017. return 0;
  20018. };
  20019. /**
  20020. * Returns null by default. Implemented by child classes
  20021. * @returns null
  20022. */
  20023. AbstractMesh.prototype.getIndices = function () {
  20024. return null;
  20025. };
  20026. /**
  20027. * Returns the array of the requested vertex data kind. Implemented by child classes
  20028. * @param kind defines the vertex data kind to use
  20029. * @returns null
  20030. */
  20031. AbstractMesh.prototype.getVerticesData = function (kind) {
  20032. return null;
  20033. };
  20034. /**
  20035. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20036. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20037. * Note that a new underlying VertexBuffer object is created each call.
  20038. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20039. * @param kind defines vertex data kind:
  20040. * * BABYLON.VertexBuffer.PositionKind
  20041. * * BABYLON.VertexBuffer.UVKind
  20042. * * BABYLON.VertexBuffer.UV2Kind
  20043. * * BABYLON.VertexBuffer.UV3Kind
  20044. * * BABYLON.VertexBuffer.UV4Kind
  20045. * * BABYLON.VertexBuffer.UV5Kind
  20046. * * BABYLON.VertexBuffer.UV6Kind
  20047. * * BABYLON.VertexBuffer.ColorKind
  20048. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20049. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20050. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20051. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20052. * @param data defines the data source
  20053. * @param updatable defines if the data must be flagged as updatable (or static)
  20054. * @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
  20055. * @returns the current mesh
  20056. */
  20057. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20058. return this;
  20059. };
  20060. /**
  20061. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20062. * If the mesh has no geometry, it is simply returned as it is.
  20063. * @param kind defines vertex data kind:
  20064. * * BABYLON.VertexBuffer.PositionKind
  20065. * * BABYLON.VertexBuffer.UVKind
  20066. * * BABYLON.VertexBuffer.UV2Kind
  20067. * * BABYLON.VertexBuffer.UV3Kind
  20068. * * BABYLON.VertexBuffer.UV4Kind
  20069. * * BABYLON.VertexBuffer.UV5Kind
  20070. * * BABYLON.VertexBuffer.UV6Kind
  20071. * * BABYLON.VertexBuffer.ColorKind
  20072. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20073. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20074. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20075. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20076. * @param data defines the data source
  20077. * @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
  20078. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20079. * @returns the current mesh
  20080. */
  20081. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20082. return this;
  20083. };
  20084. /**
  20085. * Sets the mesh indices,
  20086. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20087. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20088. * @param totalVertices Defines the total number of vertices
  20089. * @returns the current mesh
  20090. */
  20091. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20092. return this;
  20093. };
  20094. /**
  20095. * Gets a boolean indicating if specific vertex data is present
  20096. * @param kind defines the vertex data kind to use
  20097. * @returns true is data kind is present
  20098. */
  20099. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20100. return false;
  20101. };
  20102. /**
  20103. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20104. * @returns a BoundingInfo
  20105. */
  20106. AbstractMesh.prototype.getBoundingInfo = function () {
  20107. if (this._masterMesh) {
  20108. return this._masterMesh.getBoundingInfo();
  20109. }
  20110. if (!this._boundingInfo) {
  20111. // this._boundingInfo is being created here
  20112. this._updateBoundingInfo();
  20113. }
  20114. // cannot be null.
  20115. return this._boundingInfo;
  20116. };
  20117. /**
  20118. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20119. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20120. * @returns the current mesh
  20121. */
  20122. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20123. if (includeDescendants === void 0) { includeDescendants = true; }
  20124. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20125. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20126. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20127. if (maxDimension === 0) {
  20128. return this;
  20129. }
  20130. var scale = 1 / maxDimension;
  20131. this.scaling.scaleInPlace(scale);
  20132. return this;
  20133. };
  20134. /**
  20135. * Overwrite the current bounding info
  20136. * @param boundingInfo defines the new bounding info
  20137. * @returns the current mesh
  20138. */
  20139. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20140. this._boundingInfo = boundingInfo;
  20141. return this;
  20142. };
  20143. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20144. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20145. get: function () {
  20146. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. /** @hidden */
  20152. AbstractMesh.prototype._preActivate = function () {
  20153. };
  20154. /** @hidden */
  20155. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20156. };
  20157. /** @hidden */
  20158. AbstractMesh.prototype._activate = function (renderId) {
  20159. this._renderId = renderId;
  20160. };
  20161. /**
  20162. * Gets the current world matrix
  20163. * @returns a Matrix
  20164. */
  20165. AbstractMesh.prototype.getWorldMatrix = function () {
  20166. if (this._masterMesh) {
  20167. return this._masterMesh.getWorldMatrix();
  20168. }
  20169. return _super.prototype.getWorldMatrix.call(this);
  20170. };
  20171. /** @hidden */
  20172. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20173. if (this._masterMesh) {
  20174. return this._masterMesh._getWorldMatrixDeterminant();
  20175. }
  20176. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20177. };
  20178. // ================================== Point of View Movement =================================
  20179. /**
  20180. * Perform relative position change from the point of view of behind the front of the mesh.
  20181. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20182. * Supports definition of mesh facing forward or backward
  20183. * @param amountRight defines the distance on the right axis
  20184. * @param amountUp defines the distance on the up axis
  20185. * @param amountForward defines the distance on the forward axis
  20186. * @returns the current mesh
  20187. */
  20188. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20189. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20190. return this;
  20191. };
  20192. /**
  20193. * Calculate relative position change from the point of view of behind the front of the mesh.
  20194. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20195. * Supports definition of mesh facing forward or backward
  20196. * @param amountRight defines the distance on the right axis
  20197. * @param amountUp defines the distance on the up axis
  20198. * @param amountForward defines the distance on the forward axis
  20199. * @returns the new displacement vector
  20200. */
  20201. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20202. var rotMatrix = new BABYLON.Matrix();
  20203. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20204. rotQuaternion.toRotationMatrix(rotMatrix);
  20205. var translationDelta = BABYLON.Vector3.Zero();
  20206. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20207. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20208. return translationDelta;
  20209. };
  20210. // ================================== Point of View Rotation =================================
  20211. /**
  20212. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20213. * Supports definition of mesh facing forward or backward
  20214. * @param flipBack defines the flip
  20215. * @param twirlClockwise defines the twirl
  20216. * @param tiltRight defines the tilt
  20217. * @returns the current mesh
  20218. */
  20219. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20220. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20221. return this;
  20222. };
  20223. /**
  20224. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20225. * Supports definition of mesh facing forward or backward.
  20226. * @param flipBack defines the flip
  20227. * @param twirlClockwise defines the twirl
  20228. * @param tiltRight defines the tilt
  20229. * @returns the new rotation vector
  20230. */
  20231. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20232. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20233. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20234. };
  20235. /**
  20236. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20237. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20238. * @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
  20239. * @returns the new bounding vectors
  20240. */
  20241. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20242. if (includeDescendants === void 0) { includeDescendants = true; }
  20243. if (predicate === void 0) { predicate = null; }
  20244. // Ensures that all world matrix will be recomputed.
  20245. this.getScene().incrementRenderId();
  20246. this.computeWorldMatrix(true);
  20247. var min;
  20248. var max;
  20249. var boundingInfo = this.getBoundingInfo();
  20250. if (!this.subMeshes) {
  20251. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20252. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20253. }
  20254. else {
  20255. min = boundingInfo.boundingBox.minimumWorld;
  20256. max = boundingInfo.boundingBox.maximumWorld;
  20257. }
  20258. if (includeDescendants) {
  20259. var descendants = this.getDescendants(false);
  20260. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20261. var descendant = descendants_1[_i];
  20262. var childMesh = descendant;
  20263. childMesh.computeWorldMatrix(true);
  20264. // Filters meshes based on custom predicate function.
  20265. if (predicate && !predicate(childMesh)) {
  20266. continue;
  20267. }
  20268. //make sure we have the needed params to get mix and max
  20269. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20270. continue;
  20271. }
  20272. var childBoundingInfo = childMesh.getBoundingInfo();
  20273. var boundingBox = childBoundingInfo.boundingBox;
  20274. var minBox = boundingBox.minimumWorld;
  20275. var maxBox = boundingBox.maximumWorld;
  20276. BABYLON.Tools.CheckExtends(minBox, min, max);
  20277. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20278. }
  20279. }
  20280. return {
  20281. min: min,
  20282. max: max
  20283. };
  20284. };
  20285. /** @hidden */
  20286. AbstractMesh.prototype._updateBoundingInfo = function () {
  20287. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20288. this._boundingInfo.update(this.worldMatrixFromCache);
  20289. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20290. return this;
  20291. };
  20292. /** @hidden */
  20293. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20294. if (!this.subMeshes) {
  20295. return this;
  20296. }
  20297. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20298. var subMesh = this.subMeshes[subIndex];
  20299. if (!subMesh.IsGlobal) {
  20300. subMesh.updateBoundingInfo(matrix);
  20301. }
  20302. }
  20303. return this;
  20304. };
  20305. /** @hidden */
  20306. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20307. // Bounding info
  20308. this._updateBoundingInfo();
  20309. };
  20310. /**
  20311. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20312. * A mesh is in the frustum if its bounding box intersects the frustum
  20313. * @param frustumPlanes defines the frustum to test
  20314. * @returns true if the mesh is in the frustum planes
  20315. */
  20316. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20317. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20318. };
  20319. /**
  20320. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20321. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20322. * @param frustumPlanes defines the frustum to test
  20323. * @returns true if the mesh is completely in the frustum planes
  20324. */
  20325. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20326. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20327. };
  20328. /**
  20329. * True if the mesh intersects another mesh or a SolidParticle object
  20330. * @param mesh defines a target mesh or SolidParticle to test
  20331. * @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)
  20332. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20333. * @returns true if there is an intersection
  20334. */
  20335. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20336. if (precise === void 0) { precise = false; }
  20337. if (!this._boundingInfo || !mesh._boundingInfo) {
  20338. return false;
  20339. }
  20340. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20341. return true;
  20342. }
  20343. if (includeDescendants) {
  20344. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20345. var child = _a[_i];
  20346. if (child.intersectsMesh(mesh, precise, true)) {
  20347. return true;
  20348. }
  20349. }
  20350. }
  20351. return false;
  20352. };
  20353. /**
  20354. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20355. * @param point defines the point to test
  20356. * @returns true if there is an intersection
  20357. */
  20358. AbstractMesh.prototype.intersectsPoint = function (point) {
  20359. if (!this._boundingInfo) {
  20360. return false;
  20361. }
  20362. return this._boundingInfo.intersectsPoint(point);
  20363. };
  20364. /**
  20365. * Gets the current physics impostor
  20366. * @see http://doc.babylonjs.com/features/physics_engine
  20367. * @returns a physics impostor or null
  20368. */
  20369. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20370. return this.physicsImpostor;
  20371. };
  20372. /**
  20373. * Gets the position of the current mesh in camera space
  20374. * @param camera defines the camera to use
  20375. * @returns a position
  20376. */
  20377. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20378. if (camera === void 0) { camera = null; }
  20379. if (!camera) {
  20380. camera = this.getScene().activeCamera;
  20381. }
  20382. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20383. };
  20384. /**
  20385. * Returns the distance from the mesh to the active camera
  20386. * @param camera defines the camera to use
  20387. * @returns the distance
  20388. */
  20389. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20390. if (camera === void 0) { camera = null; }
  20391. if (!camera) {
  20392. camera = this.getScene().activeCamera;
  20393. }
  20394. return this.absolutePosition.subtract(camera.position).length();
  20395. };
  20396. /**
  20397. * Apply a physic impulse to the mesh
  20398. * @param force defines the force to apply
  20399. * @param contactPoint defines where to apply the force
  20400. * @returns the current mesh
  20401. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20402. */
  20403. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20404. if (!this.physicsImpostor) {
  20405. return this;
  20406. }
  20407. this.physicsImpostor.applyImpulse(force, contactPoint);
  20408. return this;
  20409. };
  20410. /**
  20411. * Creates a physic joint between two meshes
  20412. * @param otherMesh defines the other mesh to use
  20413. * @param pivot1 defines the pivot to use on this mesh
  20414. * @param pivot2 defines the pivot to use on the other mesh
  20415. * @param options defines additional options (can be plugin dependent)
  20416. * @returns the current mesh
  20417. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20418. */
  20419. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20420. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20421. return this;
  20422. }
  20423. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20424. mainPivot: pivot1,
  20425. connectedPivot: pivot2,
  20426. nativeParams: options
  20427. });
  20428. return this;
  20429. };
  20430. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20431. // Collisions
  20432. /**
  20433. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20434. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20435. */
  20436. get: function () {
  20437. return this._checkCollisions;
  20438. },
  20439. set: function (collisionEnabled) {
  20440. this._checkCollisions = collisionEnabled;
  20441. if (this.getScene().workerCollisions) {
  20442. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20443. }
  20444. },
  20445. enumerable: true,
  20446. configurable: true
  20447. });
  20448. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20449. /**
  20450. * Gets Collider object used to compute collisions (not physics)
  20451. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20452. */
  20453. get: function () {
  20454. return this._collider;
  20455. },
  20456. enumerable: true,
  20457. configurable: true
  20458. });
  20459. /**
  20460. * Move the mesh using collision engine
  20461. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20462. * @param displacement defines the requested displacement vector
  20463. * @returns the current mesh
  20464. */
  20465. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20466. var globalPosition = this.getAbsolutePosition();
  20467. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20468. if (!this._collider) {
  20469. this._collider = new BABYLON.Collider();
  20470. }
  20471. this._collider._radius = this.ellipsoid;
  20472. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20473. return this;
  20474. };
  20475. // Submeshes octree
  20476. /**
  20477. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20478. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20479. * @param maxCapacity defines the maximum size of each block (64 by default)
  20480. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20481. * @returns the new octree
  20482. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20483. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20484. */
  20485. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20486. if (maxCapacity === void 0) { maxCapacity = 64; }
  20487. if (maxDepth === void 0) { maxDepth = 2; }
  20488. if (!this._submeshesOctree) {
  20489. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20490. }
  20491. this.computeWorldMatrix(true);
  20492. var boundingInfo = this.getBoundingInfo();
  20493. // Update octree
  20494. var bbox = boundingInfo.boundingBox;
  20495. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20496. return this._submeshesOctree;
  20497. };
  20498. // Collisions
  20499. /** @hidden */
  20500. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20501. this._generatePointsArray();
  20502. if (!this._positions) {
  20503. return this;
  20504. }
  20505. // Transformation
  20506. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20507. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20508. subMesh._lastColliderWorldVertices = [];
  20509. subMesh._trianglePlanes = [];
  20510. var start = subMesh.verticesStart;
  20511. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20512. for (var i = start; i < end; i++) {
  20513. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20514. }
  20515. }
  20516. // Collide
  20517. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20518. if (collider.collisionFound) {
  20519. collider.collidedMesh = this;
  20520. }
  20521. return this;
  20522. };
  20523. /** @hidden */
  20524. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20525. var subMeshes;
  20526. var len;
  20527. // Octrees
  20528. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20529. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20530. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20531. len = intersections.length;
  20532. subMeshes = intersections.data;
  20533. }
  20534. else {
  20535. subMeshes = this.subMeshes;
  20536. len = subMeshes.length;
  20537. }
  20538. for (var index = 0; index < len; index++) {
  20539. var subMesh = subMeshes[index];
  20540. // Bounding test
  20541. if (len > 1 && !subMesh._checkCollision(collider))
  20542. continue;
  20543. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20544. }
  20545. return this;
  20546. };
  20547. /** @hidden */
  20548. AbstractMesh.prototype._checkCollision = function (collider) {
  20549. // Bounding box test
  20550. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20551. return this;
  20552. // Transformation matrix
  20553. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20554. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20555. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20556. return this;
  20557. };
  20558. // Picking
  20559. /** @hidden */
  20560. AbstractMesh.prototype._generatePointsArray = function () {
  20561. return false;
  20562. };
  20563. /**
  20564. * Checks if the passed Ray intersects with the mesh
  20565. * @param ray defines the ray to use
  20566. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20567. * @returns the picking info
  20568. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20569. */
  20570. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20571. var pickingInfo = new BABYLON.PickingInfo();
  20572. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20573. return pickingInfo;
  20574. }
  20575. if (!this._generatePointsArray()) {
  20576. return pickingInfo;
  20577. }
  20578. var intersectInfo = null;
  20579. // Octrees
  20580. var subMeshes;
  20581. var len;
  20582. if (this._submeshesOctree && this.useOctreeForPicking) {
  20583. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20584. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20585. len = intersections.length;
  20586. subMeshes = intersections.data;
  20587. }
  20588. else {
  20589. subMeshes = this.subMeshes;
  20590. len = subMeshes.length;
  20591. }
  20592. for (var index = 0; index < len; index++) {
  20593. var subMesh = subMeshes[index];
  20594. // Bounding test
  20595. if (len > 1 && !subMesh.canIntersects(ray))
  20596. continue;
  20597. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20598. if (currentIntersectInfo) {
  20599. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20600. intersectInfo = currentIntersectInfo;
  20601. intersectInfo.subMeshId = index;
  20602. if (fastCheck) {
  20603. break;
  20604. }
  20605. }
  20606. }
  20607. }
  20608. if (intersectInfo) {
  20609. // Get picked point
  20610. var world = this.getWorldMatrix();
  20611. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20612. var direction = ray.direction.clone();
  20613. direction = direction.scale(intersectInfo.distance);
  20614. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20615. var pickedPoint = worldOrigin.add(worldDirection);
  20616. // Return result
  20617. pickingInfo.hit = true;
  20618. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20619. pickingInfo.pickedPoint = pickedPoint;
  20620. pickingInfo.pickedMesh = this;
  20621. pickingInfo.bu = intersectInfo.bu || 0;
  20622. pickingInfo.bv = intersectInfo.bv || 0;
  20623. pickingInfo.faceId = intersectInfo.faceId;
  20624. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20625. return pickingInfo;
  20626. }
  20627. return pickingInfo;
  20628. };
  20629. /**
  20630. * Clones the current mesh
  20631. * @param name defines the mesh name
  20632. * @param newParent defines the new mesh parent
  20633. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20634. * @returns the new mesh
  20635. */
  20636. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20637. return null;
  20638. };
  20639. /**
  20640. * Disposes all the submeshes of the current meshnp
  20641. * @returns the current mesh
  20642. */
  20643. AbstractMesh.prototype.releaseSubMeshes = function () {
  20644. if (this.subMeshes) {
  20645. while (this.subMeshes.length) {
  20646. this.subMeshes[0].dispose();
  20647. }
  20648. }
  20649. else {
  20650. this.subMeshes = new Array();
  20651. }
  20652. return this;
  20653. };
  20654. /**
  20655. * Releases resources associated with this abstract mesh.
  20656. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20657. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20658. */
  20659. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20660. var _this = this;
  20661. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20662. var index;
  20663. // Smart Array Retainers.
  20664. this.getScene().freeActiveMeshes();
  20665. this.getScene().freeRenderingGroups();
  20666. // Action manager
  20667. if (this.actionManager !== undefined && this.actionManager !== null) {
  20668. this.actionManager.dispose();
  20669. this.actionManager = null;
  20670. }
  20671. // Skeleton
  20672. this._skeleton = null;
  20673. // Physics
  20674. if (this.physicsImpostor) {
  20675. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20676. }
  20677. // Intersections in progress
  20678. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20679. var other = this._intersectionsInProgress[index];
  20680. var pos = other._intersectionsInProgress.indexOf(this);
  20681. other._intersectionsInProgress.splice(pos, 1);
  20682. }
  20683. this._intersectionsInProgress = [];
  20684. // Lights
  20685. var lights = this.getScene().lights;
  20686. lights.forEach(function (light) {
  20687. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20688. if (meshIndex !== -1) {
  20689. light.includedOnlyMeshes.splice(meshIndex, 1);
  20690. }
  20691. meshIndex = light.excludedMeshes.indexOf(_this);
  20692. if (meshIndex !== -1) {
  20693. light.excludedMeshes.splice(meshIndex, 1);
  20694. }
  20695. // Shadow generators
  20696. var generator = light.getShadowGenerator();
  20697. if (generator) {
  20698. var shadowMap = generator.getShadowMap();
  20699. if (shadowMap && shadowMap.renderList) {
  20700. meshIndex = shadowMap.renderList.indexOf(_this);
  20701. if (meshIndex !== -1) {
  20702. shadowMap.renderList.splice(meshIndex, 1);
  20703. }
  20704. }
  20705. }
  20706. });
  20707. // Edges
  20708. if (this._edgesRenderer) {
  20709. this._edgesRenderer.dispose();
  20710. this._edgesRenderer = null;
  20711. }
  20712. // SubMeshes
  20713. if (this.getClassName() !== "InstancedMesh") {
  20714. this.releaseSubMeshes();
  20715. }
  20716. // Octree
  20717. var sceneOctree = this.getScene().selectionOctree;
  20718. if (sceneOctree !== undefined && sceneOctree !== null) {
  20719. var index = sceneOctree.dynamicContent.indexOf(this);
  20720. if (index !== -1) {
  20721. sceneOctree.dynamicContent.splice(index, 1);
  20722. }
  20723. }
  20724. // Query
  20725. var engine = this.getScene().getEngine();
  20726. if (this._occlusionQuery) {
  20727. this._isOcclusionQueryInProgress = false;
  20728. engine.deleteQuery(this._occlusionQuery);
  20729. this._occlusionQuery = null;
  20730. }
  20731. // Engine
  20732. engine.wipeCaches();
  20733. // Remove from scene
  20734. this.getScene().removeMesh(this);
  20735. if (disposeMaterialAndTextures) {
  20736. if (this.material) {
  20737. this.material.dispose(false, true);
  20738. }
  20739. }
  20740. if (!doNotRecurse) {
  20741. // Particles
  20742. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20743. if (this.getScene().particleSystems[index].emitter === this) {
  20744. this.getScene().particleSystems[index].dispose();
  20745. index--;
  20746. }
  20747. }
  20748. }
  20749. // facet data
  20750. if (this._facetDataEnabled) {
  20751. this.disableFacetData();
  20752. }
  20753. this.onAfterWorldMatrixUpdateObservable.clear();
  20754. this.onCollideObservable.clear();
  20755. this.onCollisionPositionChangeObservable.clear();
  20756. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20757. };
  20758. /**
  20759. * Adds the passed mesh as a child to the current mesh
  20760. * @param mesh defines the child mesh
  20761. * @returns the current mesh
  20762. */
  20763. AbstractMesh.prototype.addChild = function (mesh) {
  20764. mesh.setParent(this);
  20765. return this;
  20766. };
  20767. /**
  20768. * Removes the passed mesh from the current mesh children list
  20769. * @param mesh defines the child mesh
  20770. * @returns the current mesh
  20771. */
  20772. AbstractMesh.prototype.removeChild = function (mesh) {
  20773. mesh.setParent(null);
  20774. return this;
  20775. };
  20776. // Facet data
  20777. /** @hidden */
  20778. AbstractMesh.prototype._initFacetData = function () {
  20779. if (!this._facetNormals) {
  20780. this._facetNormals = new Array();
  20781. }
  20782. if (!this._facetPositions) {
  20783. this._facetPositions = new Array();
  20784. }
  20785. if (!this._facetPartitioning) {
  20786. this._facetPartitioning = new Array();
  20787. }
  20788. this._facetNb = (this.getIndices().length / 3) | 0;
  20789. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20790. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20791. for (var f = 0; f < this._facetNb; f++) {
  20792. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20793. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20794. }
  20795. this._facetDataEnabled = true;
  20796. return this;
  20797. };
  20798. /**
  20799. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20800. * This method can be called within the render loop.
  20801. * 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
  20802. * @returns the current mesh
  20803. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20804. */
  20805. AbstractMesh.prototype.updateFacetData = function () {
  20806. if (!this._facetDataEnabled) {
  20807. this._initFacetData();
  20808. }
  20809. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20810. var indices = this.getIndices();
  20811. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20812. var bInfo = this.getBoundingInfo();
  20813. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20814. // init arrays, matrix and sort function on first call
  20815. this._facetDepthSortEnabled = true;
  20816. if (indices instanceof Uint16Array) {
  20817. this._depthSortedIndices = new Uint16Array(indices);
  20818. }
  20819. else if (indices instanceof Uint32Array) {
  20820. this._depthSortedIndices = new Uint32Array(indices);
  20821. }
  20822. else {
  20823. var needs32bits = false;
  20824. for (var i = 0; i < indices.length; i++) {
  20825. if (indices[i] > 65535) {
  20826. needs32bits = true;
  20827. break;
  20828. }
  20829. }
  20830. if (needs32bits) {
  20831. this._depthSortedIndices = new Uint32Array(indices);
  20832. }
  20833. else {
  20834. this._depthSortedIndices = new Uint16Array(indices);
  20835. }
  20836. }
  20837. this._facetDepthSortFunction = function (f1, f2) {
  20838. return (f2.sqDistance - f1.sqDistance);
  20839. };
  20840. if (!this._facetDepthSortFrom) {
  20841. var camera = this.getScene().activeCamera;
  20842. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20843. }
  20844. this._depthSortedFacets = [];
  20845. for (var f = 0; f < this._facetNb; f++) {
  20846. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20847. this._depthSortedFacets.push(depthSortedFacet);
  20848. }
  20849. this._invertedMatrix = BABYLON.Matrix.Identity();
  20850. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20851. }
  20852. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20853. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20854. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20855. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20856. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20857. this._subDiv.max = this._partitioningSubdivisions;
  20858. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20859. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20860. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20861. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20862. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20863. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20864. // set the parameters for ComputeNormals()
  20865. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20866. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20867. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20868. this._facetParameters.bInfo = bInfo;
  20869. this._facetParameters.bbSize = this._bbSize;
  20870. this._facetParameters.subDiv = this._subDiv;
  20871. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20872. this._facetParameters.depthSort = this._facetDepthSort;
  20873. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20874. this.computeWorldMatrix(true);
  20875. this._worldMatrix.invertToRef(this._invertedMatrix);
  20876. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20877. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20878. }
  20879. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20880. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20881. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20882. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20883. var l = (this._depthSortedIndices.length / 3) | 0;
  20884. for (var f = 0; f < l; f++) {
  20885. var sind = this._depthSortedFacets[f].ind;
  20886. this._depthSortedIndices[f * 3] = indices[sind];
  20887. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20888. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20889. }
  20890. this.updateIndices(this._depthSortedIndices);
  20891. }
  20892. return this;
  20893. };
  20894. /**
  20895. * Returns the facetLocalNormals array.
  20896. * The normals are expressed in the mesh local spac
  20897. * @returns an array of Vector3
  20898. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20899. */
  20900. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20901. if (!this._facetNormals) {
  20902. this.updateFacetData();
  20903. }
  20904. return this._facetNormals;
  20905. };
  20906. /**
  20907. * Returns the facetLocalPositions array.
  20908. * The facet positions are expressed in the mesh local space
  20909. * @returns an array of Vector3
  20910. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20911. */
  20912. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20913. if (!this._facetPositions) {
  20914. this.updateFacetData();
  20915. }
  20916. return this._facetPositions;
  20917. };
  20918. /**
  20919. * Returns the facetLocalPartioning array
  20920. * @returns an array of array of numbers
  20921. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20922. */
  20923. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20924. if (!this._facetPartitioning) {
  20925. this.updateFacetData();
  20926. }
  20927. return this._facetPartitioning;
  20928. };
  20929. /**
  20930. * Returns the i-th facet position in the world system.
  20931. * This method allocates a new Vector3 per call
  20932. * @param i defines the facet index
  20933. * @returns a new Vector3
  20934. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20935. */
  20936. AbstractMesh.prototype.getFacetPosition = function (i) {
  20937. var pos = BABYLON.Vector3.Zero();
  20938. this.getFacetPositionToRef(i, pos);
  20939. return pos;
  20940. };
  20941. /**
  20942. * Sets the reference Vector3 with the i-th facet position in the world system
  20943. * @param i defines the facet index
  20944. * @param ref defines the target vector
  20945. * @returns the current mesh
  20946. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20947. */
  20948. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20949. var localPos = (this.getFacetLocalPositions())[i];
  20950. var world = this.getWorldMatrix();
  20951. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20952. return this;
  20953. };
  20954. /**
  20955. * Returns the i-th facet normal in the world system.
  20956. * This method allocates a new Vector3 per call
  20957. * @param i defines the facet index
  20958. * @returns a new Vector3
  20959. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20960. */
  20961. AbstractMesh.prototype.getFacetNormal = function (i) {
  20962. var norm = BABYLON.Vector3.Zero();
  20963. this.getFacetNormalToRef(i, norm);
  20964. return norm;
  20965. };
  20966. /**
  20967. * Sets the reference Vector3 with the i-th facet normal in the world system
  20968. * @param i defines the facet index
  20969. * @param ref defines the target vector
  20970. * @returns the current mesh
  20971. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20972. */
  20973. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20974. var localNorm = (this.getFacetLocalNormals())[i];
  20975. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20976. return this;
  20977. };
  20978. /**
  20979. * 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)
  20980. * @param x defines x coordinate
  20981. * @param y defines y coordinate
  20982. * @param z defines z coordinate
  20983. * @returns the array of facet indexes
  20984. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20985. */
  20986. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20987. var bInfo = this.getBoundingInfo();
  20988. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20989. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20990. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20991. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20992. return null;
  20993. }
  20994. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20995. };
  20996. /**
  20997. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20998. * @param projected sets as the (x,y,z) world projection on the facet
  20999. * @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
  21000. * @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
  21001. * @param x defines x coordinate
  21002. * @param y defines y coordinate
  21003. * @param z defines z coordinate
  21004. * @returns the face index if found (or null instead)
  21005. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21006. */
  21007. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21008. if (checkFace === void 0) { checkFace = false; }
  21009. if (facing === void 0) { facing = true; }
  21010. var world = this.getWorldMatrix();
  21011. var invMat = BABYLON.Tmp.Matrix[5];
  21012. world.invertToRef(invMat);
  21013. var invVect = BABYLON.Tmp.Vector3[8];
  21014. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21015. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21016. if (projected) {
  21017. // tranform the local computed projected vector to world coordinates
  21018. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21019. }
  21020. return closest;
  21021. };
  21022. /**
  21023. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21024. * @param projected sets as the (x,y,z) local projection on the facet
  21025. * @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
  21026. * @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
  21027. * @param x defines x coordinate
  21028. * @param y defines y coordinate
  21029. * @param z defines z coordinate
  21030. * @returns the face index if found (or null instead)
  21031. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21032. */
  21033. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21034. if (checkFace === void 0) { checkFace = false; }
  21035. if (facing === void 0) { facing = true; }
  21036. var closest = null;
  21037. var tmpx = 0.0;
  21038. var tmpy = 0.0;
  21039. var tmpz = 0.0;
  21040. var d = 0.0; // tmp dot facet normal * facet position
  21041. var t0 = 0.0;
  21042. var projx = 0.0;
  21043. var projy = 0.0;
  21044. var projz = 0.0;
  21045. // Get all the facets in the same partitioning block than (x, y, z)
  21046. var facetPositions = this.getFacetLocalPositions();
  21047. var facetNormals = this.getFacetLocalNormals();
  21048. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21049. if (!facetsInBlock) {
  21050. return null;
  21051. }
  21052. // Get the closest facet to (x, y, z)
  21053. var shortest = Number.MAX_VALUE; // init distance vars
  21054. var tmpDistance = shortest;
  21055. var fib; // current facet in the block
  21056. var norm; // current facet normal
  21057. var p0; // current facet barycenter position
  21058. // loop on all the facets in the current partitioning block
  21059. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21060. fib = facetsInBlock[idx];
  21061. norm = facetNormals[fib];
  21062. p0 = facetPositions[fib];
  21063. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21064. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21065. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21066. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21067. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21068. projx = x + norm.x * t0;
  21069. projy = y + norm.y * t0;
  21070. projz = z + norm.z * t0;
  21071. tmpx = projx - x;
  21072. tmpy = projy - y;
  21073. tmpz = projz - z;
  21074. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21075. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21076. shortest = tmpDistance;
  21077. closest = fib;
  21078. if (projected) {
  21079. projected.x = projx;
  21080. projected.y = projy;
  21081. projected.z = projz;
  21082. }
  21083. }
  21084. }
  21085. }
  21086. return closest;
  21087. };
  21088. /**
  21089. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21090. * @returns the parameters
  21091. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21092. */
  21093. AbstractMesh.prototype.getFacetDataParameters = function () {
  21094. return this._facetParameters;
  21095. };
  21096. /**
  21097. * Disables the feature FacetData and frees the related memory
  21098. * @returns the current mesh
  21099. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21100. */
  21101. AbstractMesh.prototype.disableFacetData = function () {
  21102. if (this._facetDataEnabled) {
  21103. this._facetDataEnabled = false;
  21104. this._facetPositions = new Array();
  21105. this._facetNormals = new Array();
  21106. this._facetPartitioning = new Array();
  21107. this._facetParameters = null;
  21108. this._depthSortedIndices = new Uint32Array(0);
  21109. }
  21110. return this;
  21111. };
  21112. /**
  21113. * Updates the AbstractMesh indices array
  21114. * @param indices defines the data source
  21115. * @returns the current mesh
  21116. */
  21117. AbstractMesh.prototype.updateIndices = function (indices) {
  21118. return this;
  21119. };
  21120. /**
  21121. * Creates new normals data for the mesh
  21122. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21123. * @returns the current mesh
  21124. */
  21125. AbstractMesh.prototype.createNormals = function (updatable) {
  21126. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21127. var indices = this.getIndices();
  21128. var normals;
  21129. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21130. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21131. }
  21132. else {
  21133. normals = [];
  21134. }
  21135. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21136. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21137. return this;
  21138. };
  21139. /**
  21140. * Align the mesh with a normal
  21141. * @param normal defines the normal to use
  21142. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21143. * @returns the current mesh
  21144. */
  21145. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21146. if (!upDirection) {
  21147. upDirection = BABYLON.Axis.Y;
  21148. }
  21149. var axisX = BABYLON.Tmp.Vector3[0];
  21150. var axisZ = BABYLON.Tmp.Vector3[1];
  21151. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21152. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21153. if (this.rotationQuaternion) {
  21154. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21155. }
  21156. else {
  21157. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21158. }
  21159. return this;
  21160. };
  21161. /** @hidden */
  21162. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21163. this._isOccluded = false;
  21164. };
  21165. /** No occlusion */
  21166. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21167. /** Occlusion set to optimisitic */
  21168. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21169. /** Occlusion set to strict */
  21170. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21171. /** Use an accurante occlusion algorithm */
  21172. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21173. /** Use a conservative occlusion algorithm */
  21174. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21175. return AbstractMesh;
  21176. }(BABYLON.TransformNode));
  21177. BABYLON.AbstractMesh = AbstractMesh;
  21178. })(BABYLON || (BABYLON = {}));
  21179. //# sourceMappingURL=babylon.abstractMesh.js.map
  21180. var BABYLON;
  21181. (function (BABYLON) {
  21182. /**
  21183. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21184. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21185. * 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.
  21186. */
  21187. var Light = /** @class */ (function (_super) {
  21188. __extends(Light, _super);
  21189. /**
  21190. * Creates a Light object in the scene.
  21191. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21192. * @param name The firendly name of the light
  21193. * @param scene The scene the light belongs too
  21194. */
  21195. function Light(name, scene) {
  21196. var _this = _super.call(this, name, scene) || this;
  21197. /**
  21198. * Diffuse gives the basic color to an object.
  21199. */
  21200. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21201. /**
  21202. * Specular produces a highlight color on an object.
  21203. * Note: This is note affecting PBR materials.
  21204. */
  21205. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21206. /**
  21207. * Strength of the light.
  21208. * Note: By default it is define in the framework own unit.
  21209. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21210. */
  21211. _this.intensity = 1.0;
  21212. /**
  21213. * Defines how far from the source the light is impacting in scene units.
  21214. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21215. */
  21216. _this.range = Number.MAX_VALUE;
  21217. /**
  21218. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21219. * of light.
  21220. */
  21221. _this._photometricScale = 1.0;
  21222. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21223. _this._radius = 0.00001;
  21224. /**
  21225. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21226. * exceeding the number allowed of the materials.
  21227. */
  21228. _this.renderPriority = 0;
  21229. _this._shadowEnabled = true;
  21230. _this._excludeWithLayerMask = 0;
  21231. _this._includeOnlyWithLayerMask = 0;
  21232. _this._lightmapMode = 0;
  21233. /**
  21234. * @hidden Internal use only.
  21235. */
  21236. _this._excludedMeshesIds = new Array();
  21237. /**
  21238. * @hidden Internal use only.
  21239. */
  21240. _this._includedOnlyMeshesIds = new Array();
  21241. _this.getScene().addLight(_this);
  21242. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21243. _this._buildUniformLayout();
  21244. _this.includedOnlyMeshes = new Array();
  21245. _this.excludedMeshes = new Array();
  21246. _this._resyncMeshes();
  21247. return _this;
  21248. }
  21249. Object.defineProperty(Light.prototype, "intensityMode", {
  21250. /**
  21251. * Gets the photometric scale used to interpret the intensity.
  21252. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21253. */
  21254. get: function () {
  21255. return this._intensityMode;
  21256. },
  21257. /**
  21258. * Sets the photometric scale used to interpret the intensity.
  21259. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21260. */
  21261. set: function (value) {
  21262. this._intensityMode = value;
  21263. this._computePhotometricScale();
  21264. },
  21265. enumerable: true,
  21266. configurable: true
  21267. });
  21268. ;
  21269. ;
  21270. Object.defineProperty(Light.prototype, "radius", {
  21271. /**
  21272. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21273. */
  21274. get: function () {
  21275. return this._radius;
  21276. },
  21277. /**
  21278. * sets the light radius used by PBR Materials to simulate soft area lights.
  21279. */
  21280. set: function (value) {
  21281. this._radius = value;
  21282. this._computePhotometricScale();
  21283. },
  21284. enumerable: true,
  21285. configurable: true
  21286. });
  21287. ;
  21288. ;
  21289. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21290. /**
  21291. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21292. * the current shadow generator.
  21293. */
  21294. get: function () {
  21295. return this._shadowEnabled;
  21296. },
  21297. /**
  21298. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21299. * the current shadow generator.
  21300. */
  21301. set: function (value) {
  21302. if (this._shadowEnabled === value) {
  21303. return;
  21304. }
  21305. this._shadowEnabled = value;
  21306. this._markMeshesAsLightDirty();
  21307. },
  21308. enumerable: true,
  21309. configurable: true
  21310. });
  21311. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21312. /**
  21313. * Gets the only meshes impacted by this light.
  21314. */
  21315. get: function () {
  21316. return this._includedOnlyMeshes;
  21317. },
  21318. /**
  21319. * Sets the only meshes impacted by this light.
  21320. */
  21321. set: function (value) {
  21322. this._includedOnlyMeshes = value;
  21323. this._hookArrayForIncludedOnly(value);
  21324. },
  21325. enumerable: true,
  21326. configurable: true
  21327. });
  21328. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21329. /**
  21330. * Gets the meshes not impacted by this light.
  21331. */
  21332. get: function () {
  21333. return this._excludedMeshes;
  21334. },
  21335. /**
  21336. * Sets the meshes not impacted by this light.
  21337. */
  21338. set: function (value) {
  21339. this._excludedMeshes = value;
  21340. this._hookArrayForExcluded(value);
  21341. },
  21342. enumerable: true,
  21343. configurable: true
  21344. });
  21345. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21346. /**
  21347. * Gets the layer id use to find what meshes are not impacted by the light.
  21348. * Inactive if 0
  21349. */
  21350. get: function () {
  21351. return this._excludeWithLayerMask;
  21352. },
  21353. /**
  21354. * Sets the layer id use to find what meshes are not impacted by the light.
  21355. * Inactive if 0
  21356. */
  21357. set: function (value) {
  21358. this._excludeWithLayerMask = value;
  21359. this._resyncMeshes();
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21365. /**
  21366. * Gets the layer id use to find what meshes are impacted by the light.
  21367. * Inactive if 0
  21368. */
  21369. get: function () {
  21370. return this._includeOnlyWithLayerMask;
  21371. },
  21372. /**
  21373. * Sets the layer id use to find what meshes are impacted by the light.
  21374. * Inactive if 0
  21375. */
  21376. set: function (value) {
  21377. this._includeOnlyWithLayerMask = value;
  21378. this._resyncMeshes();
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. Object.defineProperty(Light.prototype, "lightmapMode", {
  21384. /**
  21385. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21386. */
  21387. get: function () {
  21388. return this._lightmapMode;
  21389. },
  21390. /**
  21391. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21392. */
  21393. set: function (value) {
  21394. if (this._lightmapMode === value) {
  21395. return;
  21396. }
  21397. this._lightmapMode = value;
  21398. this._markMeshesAsLightDirty();
  21399. },
  21400. enumerable: true,
  21401. configurable: true
  21402. });
  21403. /**
  21404. * Returns the string "Light".
  21405. * @returns the class name
  21406. */
  21407. Light.prototype.getClassName = function () {
  21408. return "Light";
  21409. };
  21410. /**
  21411. * Converts the light information to a readable string for debug purpose.
  21412. * @param fullDetails Supports for multiple levels of logging within scene loading
  21413. * @returns the human readable light info
  21414. */
  21415. Light.prototype.toString = function (fullDetails) {
  21416. var ret = "Name: " + this.name;
  21417. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21418. if (this.animations) {
  21419. for (var i = 0; i < this.animations.length; i++) {
  21420. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21421. }
  21422. }
  21423. if (fullDetails) {
  21424. }
  21425. return ret;
  21426. };
  21427. /**
  21428. * Set the enabled state of this node.
  21429. * @param value - the new enabled state
  21430. */
  21431. Light.prototype.setEnabled = function (value) {
  21432. _super.prototype.setEnabled.call(this, value);
  21433. this._resyncMeshes();
  21434. };
  21435. /**
  21436. * Returns the Light associated shadow generator if any.
  21437. * @return the associated shadow generator.
  21438. */
  21439. Light.prototype.getShadowGenerator = function () {
  21440. return this._shadowGenerator;
  21441. };
  21442. /**
  21443. * Returns a Vector3, the absolute light position in the World.
  21444. * @returns the world space position of the light
  21445. */
  21446. Light.prototype.getAbsolutePosition = function () {
  21447. return BABYLON.Vector3.Zero();
  21448. };
  21449. /**
  21450. * Specifies if the light will affect the passed mesh.
  21451. * @param mesh The mesh to test against the light
  21452. * @return true the mesh is affected otherwise, false.
  21453. */
  21454. Light.prototype.canAffectMesh = function (mesh) {
  21455. if (!mesh) {
  21456. return true;
  21457. }
  21458. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21459. return false;
  21460. }
  21461. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21462. return false;
  21463. }
  21464. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21465. return false;
  21466. }
  21467. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21468. return false;
  21469. }
  21470. return true;
  21471. };
  21472. /**
  21473. * Computes and Returns the light World matrix.
  21474. * @returns the world matrix
  21475. */
  21476. Light.prototype.getWorldMatrix = function () {
  21477. this._currentRenderId = this.getScene().getRenderId();
  21478. this._childRenderId = this._currentRenderId;
  21479. var worldMatrix = this._getWorldMatrix();
  21480. if (this.parent && this.parent.getWorldMatrix) {
  21481. if (!this._parentedWorldMatrix) {
  21482. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21483. }
  21484. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21485. this._markSyncedWithParent();
  21486. return this._parentedWorldMatrix;
  21487. }
  21488. return worldMatrix;
  21489. };
  21490. /**
  21491. * Sort function to order lights for rendering.
  21492. * @param a First Light object to compare to second.
  21493. * @param b Second Light object to compare first.
  21494. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21495. */
  21496. Light.CompareLightsPriority = function (a, b) {
  21497. //shadow-casting lights have priority over non-shadow-casting lights
  21498. //the renderPrioirty is a secondary sort criterion
  21499. if (a.shadowEnabled !== b.shadowEnabled) {
  21500. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21501. }
  21502. return b.renderPriority - a.renderPriority;
  21503. };
  21504. /**
  21505. * Releases resources associated with this node.
  21506. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21507. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21508. */
  21509. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21510. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21511. if (this._shadowGenerator) {
  21512. this._shadowGenerator.dispose();
  21513. this._shadowGenerator = null;
  21514. }
  21515. // Animations
  21516. this.getScene().stopAnimation(this);
  21517. // Remove from meshes
  21518. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21519. var mesh = _a[_i];
  21520. mesh._removeLightSource(this);
  21521. }
  21522. this._uniformBuffer.dispose();
  21523. // Remove from scene
  21524. this.getScene().removeLight(this);
  21525. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21526. };
  21527. /**
  21528. * Returns the light type ID (integer).
  21529. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21530. */
  21531. Light.prototype.getTypeID = function () {
  21532. return 0;
  21533. };
  21534. /**
  21535. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21536. * @returns the scaled intensity in intensity mode unit
  21537. */
  21538. Light.prototype.getScaledIntensity = function () {
  21539. return this._photometricScale * this.intensity;
  21540. };
  21541. /**
  21542. * Returns a new Light object, named "name", from the current one.
  21543. * @param name The name of the cloned light
  21544. * @returns the new created light
  21545. */
  21546. Light.prototype.clone = function (name) {
  21547. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21548. if (!constructor) {
  21549. return null;
  21550. }
  21551. return BABYLON.SerializationHelper.Clone(constructor, this);
  21552. };
  21553. /**
  21554. * Serializes the current light into a Serialization object.
  21555. * @returns the serialized object.
  21556. */
  21557. Light.prototype.serialize = function () {
  21558. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21559. // Type
  21560. serializationObject.type = this.getTypeID();
  21561. // Parent
  21562. if (this.parent) {
  21563. serializationObject.parentId = this.parent.id;
  21564. }
  21565. // Inclusion / exclusions
  21566. if (this.excludedMeshes.length > 0) {
  21567. serializationObject.excludedMeshesIds = [];
  21568. this.excludedMeshes.forEach(function (mesh) {
  21569. serializationObject.excludedMeshesIds.push(mesh.id);
  21570. });
  21571. }
  21572. if (this.includedOnlyMeshes.length > 0) {
  21573. serializationObject.includedOnlyMeshesIds = [];
  21574. this.includedOnlyMeshes.forEach(function (mesh) {
  21575. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21576. });
  21577. }
  21578. // Animations
  21579. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21580. serializationObject.ranges = this.serializeAnimationRanges();
  21581. return serializationObject;
  21582. };
  21583. /**
  21584. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21585. * This new light is named "name" and added to the passed scene.
  21586. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21587. * @param name The friendly name of the light
  21588. * @param scene The scene the new light will belong to
  21589. * @returns the constructor function
  21590. */
  21591. Light.GetConstructorFromName = function (type, name, scene) {
  21592. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21593. if (constructorFunc) {
  21594. return constructorFunc;
  21595. }
  21596. // Default to no light for none present once.
  21597. return null;
  21598. };
  21599. /**
  21600. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21601. * @param parsedLight The JSON representation of the light
  21602. * @param scene The scene to create the parsed light in
  21603. * @returns the created light after parsing
  21604. */
  21605. Light.Parse = function (parsedLight, scene) {
  21606. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21607. if (!constructor) {
  21608. return null;
  21609. }
  21610. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21611. // Inclusion / exclusions
  21612. if (parsedLight.excludedMeshesIds) {
  21613. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21614. }
  21615. if (parsedLight.includedOnlyMeshesIds) {
  21616. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21617. }
  21618. // Parent
  21619. if (parsedLight.parentId) {
  21620. light._waitingParentId = parsedLight.parentId;
  21621. }
  21622. // Animations
  21623. if (parsedLight.animations) {
  21624. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21625. var parsedAnimation = parsedLight.animations[animationIndex];
  21626. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21627. }
  21628. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21629. }
  21630. if (parsedLight.autoAnimate) {
  21631. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21632. }
  21633. return light;
  21634. };
  21635. Light.prototype._hookArrayForExcluded = function (array) {
  21636. var _this = this;
  21637. var oldPush = array.push;
  21638. array.push = function () {
  21639. var items = [];
  21640. for (var _i = 0; _i < arguments.length; _i++) {
  21641. items[_i] = arguments[_i];
  21642. }
  21643. var result = oldPush.apply(array, items);
  21644. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21645. var item = items_1[_a];
  21646. item._resyncLighSource(_this);
  21647. }
  21648. return result;
  21649. };
  21650. var oldSplice = array.splice;
  21651. array.splice = function (index, deleteCount) {
  21652. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21653. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21654. var item = deleted_1[_i];
  21655. item._resyncLighSource(_this);
  21656. }
  21657. return deleted;
  21658. };
  21659. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21660. var item = array_1[_i];
  21661. item._resyncLighSource(this);
  21662. }
  21663. };
  21664. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21665. var _this = this;
  21666. var oldPush = array.push;
  21667. array.push = function () {
  21668. var items = [];
  21669. for (var _i = 0; _i < arguments.length; _i++) {
  21670. items[_i] = arguments[_i];
  21671. }
  21672. var result = oldPush.apply(array, items);
  21673. _this._resyncMeshes();
  21674. return result;
  21675. };
  21676. var oldSplice = array.splice;
  21677. array.splice = function (index, deleteCount) {
  21678. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21679. _this._resyncMeshes();
  21680. return deleted;
  21681. };
  21682. this._resyncMeshes();
  21683. };
  21684. Light.prototype._resyncMeshes = function () {
  21685. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21686. var mesh = _a[_i];
  21687. mesh._resyncLighSource(this);
  21688. }
  21689. };
  21690. /**
  21691. * Forces the meshes to update their light related information in their rendering used effects
  21692. * @hidden Internal Use Only
  21693. */
  21694. Light.prototype._markMeshesAsLightDirty = function () {
  21695. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21696. var mesh = _a[_i];
  21697. if (mesh._lightSources.indexOf(this) !== -1) {
  21698. mesh._markSubMeshesAsLightDirty();
  21699. }
  21700. }
  21701. };
  21702. /**
  21703. * Recomputes the cached photometric scale if needed.
  21704. */
  21705. Light.prototype._computePhotometricScale = function () {
  21706. this._photometricScale = this._getPhotometricScale();
  21707. this.getScene().resetCachedMaterial();
  21708. };
  21709. /**
  21710. * Returns the Photometric Scale according to the light type and intensity mode.
  21711. */
  21712. Light.prototype._getPhotometricScale = function () {
  21713. var photometricScale = 0.0;
  21714. var lightTypeID = this.getTypeID();
  21715. //get photometric mode
  21716. var photometricMode = this.intensityMode;
  21717. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21718. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21719. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21720. }
  21721. else {
  21722. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21723. }
  21724. }
  21725. //compute photometric scale
  21726. switch (lightTypeID) {
  21727. case Light.LIGHTTYPEID_POINTLIGHT:
  21728. case Light.LIGHTTYPEID_SPOTLIGHT:
  21729. switch (photometricMode) {
  21730. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21731. photometricScale = 1.0 / (4.0 * Math.PI);
  21732. break;
  21733. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21734. photometricScale = 1.0;
  21735. break;
  21736. case Light.INTENSITYMODE_LUMINANCE:
  21737. photometricScale = this.radius * this.radius;
  21738. break;
  21739. }
  21740. break;
  21741. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21742. switch (photometricMode) {
  21743. case Light.INTENSITYMODE_ILLUMINANCE:
  21744. photometricScale = 1.0;
  21745. break;
  21746. case Light.INTENSITYMODE_LUMINANCE:
  21747. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21748. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21749. var apexAngleRadians = this.radius;
  21750. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21751. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21752. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21753. photometricScale = solidAngle;
  21754. break;
  21755. }
  21756. break;
  21757. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21758. // No fall off in hemisperic light.
  21759. photometricScale = 1.0;
  21760. break;
  21761. }
  21762. return photometricScale;
  21763. };
  21764. /**
  21765. * Reorder the light in the scene according to their defined priority.
  21766. * @hidden Internal Use Only
  21767. */
  21768. Light.prototype._reorderLightsInScene = function () {
  21769. var scene = this.getScene();
  21770. if (this._renderPriority != 0) {
  21771. scene.requireLightSorting = true;
  21772. }
  21773. this.getScene().sortLightsByPriority();
  21774. };
  21775. //lightmapMode Consts
  21776. /**
  21777. * If every light affecting the material is in this lightmapMode,
  21778. * material.lightmapTexture adds or multiplies
  21779. * (depends on material.useLightmapAsShadowmap)
  21780. * after every other light calculations.
  21781. */
  21782. Light.LIGHTMAP_DEFAULT = 0;
  21783. /**
  21784. * material.lightmapTexture as only diffuse lighting from this light
  21785. * adds only specular lighting from this light
  21786. * adds dynamic shadows
  21787. */
  21788. Light.LIGHTMAP_SPECULAR = 1;
  21789. /**
  21790. * material.lightmapTexture as only lighting
  21791. * no light calculation from this light
  21792. * only adds dynamic shadows from this light
  21793. */
  21794. Light.LIGHTMAP_SHADOWSONLY = 2;
  21795. // Intensity Mode Consts
  21796. /**
  21797. * Each light type uses the default quantity according to its type:
  21798. * point/spot lights use luminous intensity
  21799. * directional lights use illuminance
  21800. */
  21801. Light.INTENSITYMODE_AUTOMATIC = 0;
  21802. /**
  21803. * lumen (lm)
  21804. */
  21805. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21806. /**
  21807. * candela (lm/sr)
  21808. */
  21809. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21810. /**
  21811. * lux (lm/m^2)
  21812. */
  21813. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21814. /**
  21815. * nit (cd/m^2)
  21816. */
  21817. Light.INTENSITYMODE_LUMINANCE = 4;
  21818. // Light types ids const.
  21819. /**
  21820. * Light type const id of the point light.
  21821. */
  21822. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21823. /**
  21824. * Light type const id of the directional light.
  21825. */
  21826. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21827. /**
  21828. * Light type const id of the spot light.
  21829. */
  21830. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21831. /**
  21832. * Light type const id of the hemispheric light.
  21833. */
  21834. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21835. __decorate([
  21836. BABYLON.serializeAsColor3()
  21837. ], Light.prototype, "diffuse", void 0);
  21838. __decorate([
  21839. BABYLON.serializeAsColor3()
  21840. ], Light.prototype, "specular", void 0);
  21841. __decorate([
  21842. BABYLON.serialize()
  21843. ], Light.prototype, "intensity", void 0);
  21844. __decorate([
  21845. BABYLON.serialize()
  21846. ], Light.prototype, "range", void 0);
  21847. __decorate([
  21848. BABYLON.serialize()
  21849. ], Light.prototype, "intensityMode", null);
  21850. __decorate([
  21851. BABYLON.serialize()
  21852. ], Light.prototype, "radius", null);
  21853. __decorate([
  21854. BABYLON.serialize()
  21855. ], Light.prototype, "_renderPriority", void 0);
  21856. __decorate([
  21857. BABYLON.expandToProperty("_reorderLightsInScene")
  21858. ], Light.prototype, "renderPriority", void 0);
  21859. __decorate([
  21860. BABYLON.serialize("shadowEnabled")
  21861. ], Light.prototype, "_shadowEnabled", void 0);
  21862. __decorate([
  21863. BABYLON.serialize("excludeWithLayerMask")
  21864. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21865. __decorate([
  21866. BABYLON.serialize("includeOnlyWithLayerMask")
  21867. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21868. __decorate([
  21869. BABYLON.serialize("lightmapMode")
  21870. ], Light.prototype, "_lightmapMode", void 0);
  21871. return Light;
  21872. }(BABYLON.Node));
  21873. BABYLON.Light = Light;
  21874. })(BABYLON || (BABYLON = {}));
  21875. //# sourceMappingURL=babylon.light.js.map
  21876. var BABYLON;
  21877. (function (BABYLON) {
  21878. var Camera = /** @class */ (function (_super) {
  21879. __extends(Camera, _super);
  21880. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21881. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21882. var _this = _super.call(this, name, scene) || this;
  21883. /**
  21884. * The vector the camera should consider as up.
  21885. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21886. */
  21887. _this.upVector = BABYLON.Vector3.Up();
  21888. _this.orthoLeft = null;
  21889. _this.orthoRight = null;
  21890. _this.orthoBottom = null;
  21891. _this.orthoTop = null;
  21892. /**
  21893. * FOV is set in Radians. (default is 0.8)
  21894. */
  21895. _this.fov = 0.8;
  21896. _this.minZ = 1;
  21897. _this.maxZ = 10000.0;
  21898. _this.inertia = 0.9;
  21899. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21900. _this.isIntermediate = false;
  21901. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21902. /**
  21903. * Restricts the camera to viewing objects with the same layerMask.
  21904. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21905. */
  21906. _this.layerMask = 0x0FFFFFFF;
  21907. /**
  21908. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21909. */
  21910. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21911. // Camera rig members
  21912. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21913. _this._rigCameras = new Array();
  21914. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21915. _this._skipRendering = false;
  21916. _this.customRenderTargets = new Array();
  21917. // Observables
  21918. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21919. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21920. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21921. _this.onRestoreStateObservable = new BABYLON.Observable();
  21922. // Cache
  21923. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21924. _this._projectionMatrix = new BABYLON.Matrix();
  21925. _this._doNotComputeProjectionMatrix = false;
  21926. _this._worldMatrix = BABYLON.Matrix.Identity();
  21927. _this._postProcesses = new Array();
  21928. _this._transformMatrix = BABYLON.Matrix.Zero();
  21929. _this._activeMeshes = new BABYLON.SmartArray(256);
  21930. _this._globalPosition = BABYLON.Vector3.Zero();
  21931. _this._refreshFrustumPlanes = true;
  21932. _this.getScene().addCamera(_this);
  21933. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21934. _this.getScene().activeCamera = _this;
  21935. }
  21936. _this.position = position;
  21937. return _this;
  21938. }
  21939. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21940. get: function () {
  21941. return Camera._PERSPECTIVE_CAMERA;
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21947. get: function () {
  21948. return Camera._ORTHOGRAPHIC_CAMERA;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21954. /**
  21955. * This is the default FOV mode for perspective cameras.
  21956. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21957. *
  21958. */
  21959. get: function () {
  21960. return Camera._FOVMODE_VERTICAL_FIXED;
  21961. },
  21962. enumerable: true,
  21963. configurable: true
  21964. });
  21965. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21966. /**
  21967. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21968. *
  21969. */
  21970. get: function () {
  21971. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21972. },
  21973. enumerable: true,
  21974. configurable: true
  21975. });
  21976. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21977. get: function () {
  21978. return Camera._RIG_MODE_NONE;
  21979. },
  21980. enumerable: true,
  21981. configurable: true
  21982. });
  21983. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21984. get: function () {
  21985. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21991. get: function () {
  21992. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21993. },
  21994. enumerable: true,
  21995. configurable: true
  21996. });
  21997. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21998. get: function () {
  21999. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22005. get: function () {
  22006. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22007. },
  22008. enumerable: true,
  22009. configurable: true
  22010. });
  22011. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22012. get: function () {
  22013. return Camera._RIG_MODE_VR;
  22014. },
  22015. enumerable: true,
  22016. configurable: true
  22017. });
  22018. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22019. get: function () {
  22020. return Camera._RIG_MODE_WEBVR;
  22021. },
  22022. enumerable: true,
  22023. configurable: true
  22024. });
  22025. /**
  22026. * Store current camera state (fov, position, etc..)
  22027. */
  22028. Camera.prototype.storeState = function () {
  22029. this._stateStored = true;
  22030. this._storedFov = this.fov;
  22031. return this;
  22032. };
  22033. /**
  22034. * Restores the camera state values if it has been stored. You must call storeState() first
  22035. */
  22036. Camera.prototype._restoreStateValues = function () {
  22037. if (!this._stateStored) {
  22038. return false;
  22039. }
  22040. this.fov = this._storedFov;
  22041. return true;
  22042. };
  22043. /**
  22044. * Restored camera state. You must call storeState() first
  22045. */
  22046. Camera.prototype.restoreState = function () {
  22047. if (this._restoreStateValues()) {
  22048. this.onRestoreStateObservable.notifyObservers(this);
  22049. return true;
  22050. }
  22051. return false;
  22052. };
  22053. Camera.prototype.getClassName = function () {
  22054. return "Camera";
  22055. };
  22056. /**
  22057. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22058. */
  22059. Camera.prototype.toString = function (fullDetails) {
  22060. var ret = "Name: " + this.name;
  22061. ret += ", type: " + this.getClassName();
  22062. if (this.animations) {
  22063. for (var i = 0; i < this.animations.length; i++) {
  22064. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22065. }
  22066. }
  22067. if (fullDetails) {
  22068. }
  22069. return ret;
  22070. };
  22071. Object.defineProperty(Camera.prototype, "globalPosition", {
  22072. get: function () {
  22073. return this._globalPosition;
  22074. },
  22075. enumerable: true,
  22076. configurable: true
  22077. });
  22078. Camera.prototype.getActiveMeshes = function () {
  22079. return this._activeMeshes;
  22080. };
  22081. Camera.prototype.isActiveMesh = function (mesh) {
  22082. return (this._activeMeshes.indexOf(mesh) !== -1);
  22083. };
  22084. /**
  22085. * Is this camera ready to be used/rendered
  22086. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22087. * @return true if the camera is ready
  22088. */
  22089. Camera.prototype.isReady = function (completeCheck) {
  22090. if (completeCheck === void 0) { completeCheck = false; }
  22091. if (completeCheck) {
  22092. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22093. var pp = _a[_i];
  22094. if (pp && !pp.isReady()) {
  22095. return false;
  22096. }
  22097. }
  22098. }
  22099. return _super.prototype.isReady.call(this, completeCheck);
  22100. };
  22101. //Cache
  22102. Camera.prototype._initCache = function () {
  22103. _super.prototype._initCache.call(this);
  22104. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22105. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22106. this._cache.mode = undefined;
  22107. this._cache.minZ = undefined;
  22108. this._cache.maxZ = undefined;
  22109. this._cache.fov = undefined;
  22110. this._cache.fovMode = undefined;
  22111. this._cache.aspectRatio = undefined;
  22112. this._cache.orthoLeft = undefined;
  22113. this._cache.orthoRight = undefined;
  22114. this._cache.orthoBottom = undefined;
  22115. this._cache.orthoTop = undefined;
  22116. this._cache.renderWidth = undefined;
  22117. this._cache.renderHeight = undefined;
  22118. };
  22119. Camera.prototype._updateCache = function (ignoreParentClass) {
  22120. if (!ignoreParentClass) {
  22121. _super.prototype._updateCache.call(this);
  22122. }
  22123. this._cache.position.copyFrom(this.position);
  22124. this._cache.upVector.copyFrom(this.upVector);
  22125. };
  22126. // Synchronized
  22127. Camera.prototype._isSynchronized = function () {
  22128. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22129. };
  22130. Camera.prototype._isSynchronizedViewMatrix = function () {
  22131. if (!_super.prototype._isSynchronized.call(this))
  22132. return false;
  22133. return this._cache.position.equals(this.position)
  22134. && this._cache.upVector.equals(this.upVector)
  22135. && this.isSynchronizedWithParent();
  22136. };
  22137. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22138. var check = this._cache.mode === this.mode
  22139. && this._cache.minZ === this.minZ
  22140. && this._cache.maxZ === this.maxZ;
  22141. if (!check) {
  22142. return false;
  22143. }
  22144. var engine = this.getEngine();
  22145. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22146. check = this._cache.fov === this.fov
  22147. && this._cache.fovMode === this.fovMode
  22148. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22149. }
  22150. else {
  22151. check = this._cache.orthoLeft === this.orthoLeft
  22152. && this._cache.orthoRight === this.orthoRight
  22153. && this._cache.orthoBottom === this.orthoBottom
  22154. && this._cache.orthoTop === this.orthoTop
  22155. && this._cache.renderWidth === engine.getRenderWidth()
  22156. && this._cache.renderHeight === engine.getRenderHeight();
  22157. }
  22158. return check;
  22159. };
  22160. // Controls
  22161. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22162. };
  22163. Camera.prototype.detachControl = function (element) {
  22164. };
  22165. Camera.prototype.update = function () {
  22166. this._checkInputs();
  22167. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22168. this._updateRigCameras();
  22169. }
  22170. };
  22171. Camera.prototype._checkInputs = function () {
  22172. this.onAfterCheckInputsObservable.notifyObservers(this);
  22173. };
  22174. Object.defineProperty(Camera.prototype, "rigCameras", {
  22175. get: function () {
  22176. return this._rigCameras;
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22182. get: function () {
  22183. return this._rigPostProcess;
  22184. },
  22185. enumerable: true,
  22186. configurable: true
  22187. });
  22188. /**
  22189. * Internal, gets the first post proces.
  22190. * @returns the first post process to be run on this camera.
  22191. */
  22192. Camera.prototype._getFirstPostProcess = function () {
  22193. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22194. if (this._postProcesses[ppIndex] !== null) {
  22195. return this._postProcesses[ppIndex];
  22196. }
  22197. }
  22198. return null;
  22199. };
  22200. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22201. // invalidate framebuffer
  22202. var firstPostProcess = this._getFirstPostProcess();
  22203. if (firstPostProcess) {
  22204. firstPostProcess.markTextureDirty();
  22205. }
  22206. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22207. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22208. var cam = this._rigCameras[i];
  22209. var rigPostProcess = cam._rigPostProcess;
  22210. // for VR rig, there does not have to be a post process
  22211. if (rigPostProcess) {
  22212. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22213. if (isPass) {
  22214. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22215. cam.isIntermediate = this._postProcesses.length === 0;
  22216. }
  22217. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22218. rigPostProcess.markTextureDirty();
  22219. }
  22220. else {
  22221. cam._postProcesses = this._postProcesses.slice(0);
  22222. }
  22223. }
  22224. };
  22225. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22226. if (insertAt === void 0) { insertAt = null; }
  22227. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22228. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22229. return 0;
  22230. }
  22231. if (insertAt == null || insertAt < 0) {
  22232. this._postProcesses.push(postProcess);
  22233. }
  22234. else if (this._postProcesses[insertAt] === null) {
  22235. this._postProcesses[insertAt] = postProcess;
  22236. }
  22237. else {
  22238. this._postProcesses.splice(insertAt, 0, postProcess);
  22239. }
  22240. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22241. return this._postProcesses.indexOf(postProcess);
  22242. };
  22243. Camera.prototype.detachPostProcess = function (postProcess) {
  22244. var idx = this._postProcesses.indexOf(postProcess);
  22245. if (idx !== -1) {
  22246. this._postProcesses[idx] = null;
  22247. }
  22248. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22249. };
  22250. Camera.prototype.getWorldMatrix = function () {
  22251. if (this._isSynchronizedViewMatrix()) {
  22252. return this._worldMatrix;
  22253. }
  22254. // Getting the the view matrix will also compute the world matrix.
  22255. this.getViewMatrix();
  22256. return this._worldMatrix;
  22257. };
  22258. Camera.prototype._getViewMatrix = function () {
  22259. return BABYLON.Matrix.Identity();
  22260. };
  22261. Camera.prototype.getViewMatrix = function (force) {
  22262. if (!force && this._isSynchronizedViewMatrix()) {
  22263. return this._computedViewMatrix;
  22264. }
  22265. this.updateCache();
  22266. this._computedViewMatrix = this._getViewMatrix();
  22267. this._currentRenderId = this.getScene().getRenderId();
  22268. this._childRenderId = this._currentRenderId;
  22269. this._refreshFrustumPlanes = true;
  22270. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22271. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22272. }
  22273. this.onViewMatrixChangedObservable.notifyObservers(this);
  22274. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22275. return this._computedViewMatrix;
  22276. };
  22277. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22278. this._doNotComputeProjectionMatrix = true;
  22279. if (projection !== undefined) {
  22280. this._projectionMatrix = projection;
  22281. }
  22282. };
  22283. ;
  22284. Camera.prototype.unfreezeProjectionMatrix = function () {
  22285. this._doNotComputeProjectionMatrix = false;
  22286. };
  22287. ;
  22288. Camera.prototype.getProjectionMatrix = function (force) {
  22289. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22290. return this._projectionMatrix;
  22291. }
  22292. // Cache
  22293. this._cache.mode = this.mode;
  22294. this._cache.minZ = this.minZ;
  22295. this._cache.maxZ = this.maxZ;
  22296. // Matrix
  22297. this._refreshFrustumPlanes = true;
  22298. var engine = this.getEngine();
  22299. var scene = this.getScene();
  22300. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22301. this._cache.fov = this.fov;
  22302. this._cache.fovMode = this.fovMode;
  22303. this._cache.aspectRatio = engine.getAspectRatio(this);
  22304. if (this.minZ <= 0) {
  22305. this.minZ = 0.1;
  22306. }
  22307. if (scene.useRightHandedSystem) {
  22308. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22309. }
  22310. else {
  22311. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22312. }
  22313. }
  22314. else {
  22315. var halfWidth = engine.getRenderWidth() / 2.0;
  22316. var halfHeight = engine.getRenderHeight() / 2.0;
  22317. if (scene.useRightHandedSystem) {
  22318. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22319. }
  22320. else {
  22321. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22322. }
  22323. this._cache.orthoLeft = this.orthoLeft;
  22324. this._cache.orthoRight = this.orthoRight;
  22325. this._cache.orthoBottom = this.orthoBottom;
  22326. this._cache.orthoTop = this.orthoTop;
  22327. this._cache.renderWidth = engine.getRenderWidth();
  22328. this._cache.renderHeight = engine.getRenderHeight();
  22329. }
  22330. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22331. return this._projectionMatrix;
  22332. };
  22333. Camera.prototype.getTranformationMatrix = function () {
  22334. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22335. return this._transformMatrix;
  22336. };
  22337. Camera.prototype.updateFrustumPlanes = function () {
  22338. if (!this._refreshFrustumPlanes) {
  22339. return;
  22340. }
  22341. this.getTranformationMatrix();
  22342. if (!this._frustumPlanes) {
  22343. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22344. }
  22345. else {
  22346. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22347. }
  22348. this._refreshFrustumPlanes = false;
  22349. };
  22350. Camera.prototype.isInFrustum = function (target) {
  22351. this.updateFrustumPlanes();
  22352. return target.isInFrustum(this._frustumPlanes);
  22353. };
  22354. Camera.prototype.isCompletelyInFrustum = function (target) {
  22355. this.updateFrustumPlanes();
  22356. return target.isCompletelyInFrustum(this._frustumPlanes);
  22357. };
  22358. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22359. if (length === void 0) { length = 100; }
  22360. if (!transform) {
  22361. transform = this.getWorldMatrix();
  22362. }
  22363. if (!origin) {
  22364. origin = this.position;
  22365. }
  22366. var forward = new BABYLON.Vector3(0, 0, 1);
  22367. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22368. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22369. return new BABYLON.Ray(origin, direction, length);
  22370. };
  22371. /**
  22372. * Releases resources associated with this node.
  22373. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22374. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22375. */
  22376. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22377. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22378. // Observables
  22379. this.onViewMatrixChangedObservable.clear();
  22380. this.onProjectionMatrixChangedObservable.clear();
  22381. this.onAfterCheckInputsObservable.clear();
  22382. this.onRestoreStateObservable.clear();
  22383. // Inputs
  22384. if (this.inputs) {
  22385. this.inputs.clear();
  22386. }
  22387. // Animations
  22388. this.getScene().stopAnimation(this);
  22389. // Remove from scene
  22390. this.getScene().removeCamera(this);
  22391. while (this._rigCameras.length > 0) {
  22392. var camera = this._rigCameras.pop();
  22393. if (camera) {
  22394. camera.dispose();
  22395. }
  22396. }
  22397. // Postprocesses
  22398. if (this._rigPostProcess) {
  22399. this._rigPostProcess.dispose(this);
  22400. this._rigPostProcess = null;
  22401. this._postProcesses = [];
  22402. }
  22403. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22404. this._rigPostProcess = null;
  22405. this._postProcesses = [];
  22406. }
  22407. else {
  22408. var i = this._postProcesses.length;
  22409. while (--i >= 0) {
  22410. var postProcess = this._postProcesses[i];
  22411. if (postProcess) {
  22412. postProcess.dispose(this);
  22413. }
  22414. }
  22415. }
  22416. // Render targets
  22417. var i = this.customRenderTargets.length;
  22418. while (--i >= 0) {
  22419. this.customRenderTargets[i].dispose();
  22420. }
  22421. this.customRenderTargets = [];
  22422. // Active Meshes
  22423. this._activeMeshes.dispose();
  22424. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22425. };
  22426. Object.defineProperty(Camera.prototype, "leftCamera", {
  22427. // ---- Camera rigs section ----
  22428. get: function () {
  22429. if (this._rigCameras.length < 1) {
  22430. return null;
  22431. }
  22432. return this._rigCameras[0];
  22433. },
  22434. enumerable: true,
  22435. configurable: true
  22436. });
  22437. Object.defineProperty(Camera.prototype, "rightCamera", {
  22438. get: function () {
  22439. if (this._rigCameras.length < 2) {
  22440. return null;
  22441. }
  22442. return this._rigCameras[1];
  22443. },
  22444. enumerable: true,
  22445. configurable: true
  22446. });
  22447. Camera.prototype.getLeftTarget = function () {
  22448. if (this._rigCameras.length < 1) {
  22449. return null;
  22450. }
  22451. return this._rigCameras[0].getTarget();
  22452. };
  22453. Camera.prototype.getRightTarget = function () {
  22454. if (this._rigCameras.length < 2) {
  22455. return null;
  22456. }
  22457. return this._rigCameras[1].getTarget();
  22458. };
  22459. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22460. if (this.cameraRigMode === mode) {
  22461. return;
  22462. }
  22463. while (this._rigCameras.length > 0) {
  22464. var camera = this._rigCameras.pop();
  22465. if (camera) {
  22466. camera.dispose();
  22467. }
  22468. }
  22469. this.cameraRigMode = mode;
  22470. this._cameraRigParams = {};
  22471. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22472. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22473. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22474. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22475. // create the rig cameras, unless none
  22476. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22477. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22478. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22479. if (leftCamera && rightCamera) {
  22480. this._rigCameras.push(leftCamera);
  22481. this._rigCameras.push(rightCamera);
  22482. }
  22483. }
  22484. switch (this.cameraRigMode) {
  22485. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22486. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22487. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22488. break;
  22489. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22490. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22491. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22492. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22493. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22494. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22495. break;
  22496. case Camera.RIG_MODE_VR:
  22497. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22498. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22499. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22500. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22501. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22502. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22503. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22504. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22505. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22506. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22507. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22508. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22509. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22510. if (metrics.compensateDistortion) {
  22511. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22512. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22513. }
  22514. break;
  22515. case Camera.RIG_MODE_WEBVR:
  22516. if (rigParams.vrDisplay) {
  22517. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22518. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22519. //Left eye
  22520. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22521. this._rigCameras[0].setCameraRigParameter("left", true);
  22522. //leaving this for future reference
  22523. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22524. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22525. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22526. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22527. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22528. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22529. this._rigCameras[0].parent = this;
  22530. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22531. //Right eye
  22532. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22533. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22534. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22535. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22536. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22537. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22538. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22539. this._rigCameras[1].parent = this;
  22540. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22541. if (Camera.UseAlternateWebVRRendering) {
  22542. this._rigCameras[1]._skipRendering = true;
  22543. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22544. }
  22545. }
  22546. break;
  22547. }
  22548. this._cascadePostProcessesToRigCams();
  22549. this.update();
  22550. };
  22551. Camera.prototype._getVRProjectionMatrix = function () {
  22552. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22553. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22554. return this._projectionMatrix;
  22555. };
  22556. Camera.prototype._updateCameraRotationMatrix = function () {
  22557. //Here for WebVR
  22558. };
  22559. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22560. //Here for WebVR
  22561. };
  22562. /**
  22563. * This function MUST be overwritten by the different WebVR cameras available.
  22564. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22565. */
  22566. Camera.prototype._getWebVRProjectionMatrix = function () {
  22567. return BABYLON.Matrix.Identity();
  22568. };
  22569. /**
  22570. * This function MUST be overwritten by the different WebVR cameras available.
  22571. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22572. */
  22573. Camera.prototype._getWebVRViewMatrix = function () {
  22574. return BABYLON.Matrix.Identity();
  22575. };
  22576. Camera.prototype.setCameraRigParameter = function (name, value) {
  22577. if (!this._cameraRigParams) {
  22578. this._cameraRigParams = {};
  22579. }
  22580. this._cameraRigParams[name] = value;
  22581. //provisionnally:
  22582. if (name === "interaxialDistance") {
  22583. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22584. }
  22585. };
  22586. /**
  22587. * needs to be overridden by children so sub has required properties to be copied
  22588. */
  22589. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22590. return null;
  22591. };
  22592. /**
  22593. * May need to be overridden by children
  22594. */
  22595. Camera.prototype._updateRigCameras = function () {
  22596. for (var i = 0; i < this._rigCameras.length; i++) {
  22597. this._rigCameras[i].minZ = this.minZ;
  22598. this._rigCameras[i].maxZ = this.maxZ;
  22599. this._rigCameras[i].fov = this.fov;
  22600. }
  22601. // only update viewport when ANAGLYPH
  22602. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22603. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22604. }
  22605. };
  22606. Camera.prototype._setupInputs = function () {
  22607. };
  22608. Camera.prototype.serialize = function () {
  22609. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22610. // Type
  22611. serializationObject.type = this.getClassName();
  22612. // Parent
  22613. if (this.parent) {
  22614. serializationObject.parentId = this.parent.id;
  22615. }
  22616. if (this.inputs) {
  22617. this.inputs.serialize(serializationObject);
  22618. }
  22619. // Animations
  22620. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22621. serializationObject.ranges = this.serializeAnimationRanges();
  22622. return serializationObject;
  22623. };
  22624. Camera.prototype.clone = function (name) {
  22625. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22626. };
  22627. Camera.prototype.getDirection = function (localAxis) {
  22628. var result = BABYLON.Vector3.Zero();
  22629. this.getDirectionToRef(localAxis, result);
  22630. return result;
  22631. };
  22632. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22633. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22634. };
  22635. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22636. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22637. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22638. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22639. interaxial_distance: interaxial_distance,
  22640. isStereoscopicSideBySide: isStereoscopicSideBySide
  22641. });
  22642. if (constructorFunc) {
  22643. return constructorFunc;
  22644. }
  22645. // Default to universal camera
  22646. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22647. };
  22648. Camera.prototype.computeWorldMatrix = function () {
  22649. return this.getWorldMatrix();
  22650. };
  22651. Camera.Parse = function (parsedCamera, scene) {
  22652. var type = parsedCamera.type;
  22653. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22654. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22655. // Parent
  22656. if (parsedCamera.parentId) {
  22657. camera._waitingParentId = parsedCamera.parentId;
  22658. }
  22659. //If camera has an input manager, let it parse inputs settings
  22660. if (camera.inputs) {
  22661. camera.inputs.parse(parsedCamera);
  22662. camera._setupInputs();
  22663. }
  22664. if (camera.setPosition) { // need to force position
  22665. camera.position.copyFromFloats(0, 0, 0);
  22666. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22667. }
  22668. // Target
  22669. if (parsedCamera.target) {
  22670. if (camera.setTarget) {
  22671. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22672. }
  22673. }
  22674. // Apply 3d rig, when found
  22675. if (parsedCamera.cameraRigMode) {
  22676. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22677. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22678. }
  22679. // Animations
  22680. if (parsedCamera.animations) {
  22681. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22682. var parsedAnimation = parsedCamera.animations[animationIndex];
  22683. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22684. }
  22685. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22686. }
  22687. if (parsedCamera.autoAnimate) {
  22688. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22689. }
  22690. return camera;
  22691. };
  22692. // Statics
  22693. Camera._PERSPECTIVE_CAMERA = 0;
  22694. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22695. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22696. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22697. Camera._RIG_MODE_NONE = 0;
  22698. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22699. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22700. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22701. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22702. Camera._RIG_MODE_VR = 20;
  22703. Camera._RIG_MODE_WEBVR = 21;
  22704. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22705. Camera.UseAlternateWebVRRendering = false;
  22706. __decorate([
  22707. BABYLON.serializeAsVector3()
  22708. ], Camera.prototype, "position", void 0);
  22709. __decorate([
  22710. BABYLON.serializeAsVector3()
  22711. ], Camera.prototype, "upVector", void 0);
  22712. __decorate([
  22713. BABYLON.serialize()
  22714. ], Camera.prototype, "orthoLeft", void 0);
  22715. __decorate([
  22716. BABYLON.serialize()
  22717. ], Camera.prototype, "orthoRight", void 0);
  22718. __decorate([
  22719. BABYLON.serialize()
  22720. ], Camera.prototype, "orthoBottom", void 0);
  22721. __decorate([
  22722. BABYLON.serialize()
  22723. ], Camera.prototype, "orthoTop", void 0);
  22724. __decorate([
  22725. BABYLON.serialize()
  22726. ], Camera.prototype, "fov", void 0);
  22727. __decorate([
  22728. BABYLON.serialize()
  22729. ], Camera.prototype, "minZ", void 0);
  22730. __decorate([
  22731. BABYLON.serialize()
  22732. ], Camera.prototype, "maxZ", void 0);
  22733. __decorate([
  22734. BABYLON.serialize()
  22735. ], Camera.prototype, "inertia", void 0);
  22736. __decorate([
  22737. BABYLON.serialize()
  22738. ], Camera.prototype, "mode", void 0);
  22739. __decorate([
  22740. BABYLON.serialize()
  22741. ], Camera.prototype, "layerMask", void 0);
  22742. __decorate([
  22743. BABYLON.serialize()
  22744. ], Camera.prototype, "fovMode", void 0);
  22745. __decorate([
  22746. BABYLON.serialize()
  22747. ], Camera.prototype, "cameraRigMode", void 0);
  22748. __decorate([
  22749. BABYLON.serialize()
  22750. ], Camera.prototype, "interaxialDistance", void 0);
  22751. __decorate([
  22752. BABYLON.serialize()
  22753. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22754. return Camera;
  22755. }(BABYLON.Node));
  22756. BABYLON.Camera = Camera;
  22757. })(BABYLON || (BABYLON = {}));
  22758. //# sourceMappingURL=babylon.camera.js.map
  22759. var BABYLON;
  22760. (function (BABYLON) {
  22761. var RenderingManager = /** @class */ (function () {
  22762. function RenderingManager(scene) {
  22763. this._renderingGroups = new Array();
  22764. this._autoClearDepthStencil = {};
  22765. this._customOpaqueSortCompareFn = {};
  22766. this._customAlphaTestSortCompareFn = {};
  22767. this._customTransparentSortCompareFn = {};
  22768. this._renderinGroupInfo = null;
  22769. this._scene = scene;
  22770. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22771. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22772. }
  22773. }
  22774. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22775. if (depth === void 0) { depth = true; }
  22776. if (stencil === void 0) { stencil = true; }
  22777. if (this._depthStencilBufferAlreadyCleaned) {
  22778. return;
  22779. }
  22780. this._scene.getEngine().clear(null, false, depth, stencil);
  22781. this._depthStencilBufferAlreadyCleaned = true;
  22782. };
  22783. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22784. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22785. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22786. var info = null;
  22787. if (observable) {
  22788. if (!this._renderinGroupInfo) {
  22789. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22790. }
  22791. info = this._renderinGroupInfo;
  22792. info.scene = this._scene;
  22793. info.camera = this._scene.activeCamera;
  22794. }
  22795. // Dispatch sprites
  22796. if (renderSprites) {
  22797. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22798. var manager = this._scene.spriteManagers[index];
  22799. this.dispatchSprites(manager);
  22800. }
  22801. }
  22802. // Render
  22803. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22804. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22805. var renderingGroup = this._renderingGroups[index];
  22806. if (!renderingGroup && !observable)
  22807. continue;
  22808. var renderingGroupMask = 0;
  22809. // Fire PRECLEAR stage
  22810. if (observable && info) {
  22811. renderingGroupMask = Math.pow(2, index);
  22812. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22813. info.renderingGroupId = index;
  22814. observable.notifyObservers(info, renderingGroupMask);
  22815. }
  22816. // Clear depth/stencil if needed
  22817. if (RenderingManager.AUTOCLEAR) {
  22818. var autoClear = this._autoClearDepthStencil[index];
  22819. if (autoClear && autoClear.autoClear) {
  22820. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22821. }
  22822. }
  22823. if (observable && info) {
  22824. // Fire PREOPAQUE stage
  22825. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22826. observable.notifyObservers(info, renderingGroupMask);
  22827. // Fire PRETRANSPARENT stage
  22828. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22829. observable.notifyObservers(info, renderingGroupMask);
  22830. }
  22831. if (renderingGroup) {
  22832. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22833. var step = _a[_i];
  22834. step.action(index);
  22835. }
  22836. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22837. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22838. var step = _c[_b];
  22839. step.action(index);
  22840. }
  22841. }
  22842. // Fire POSTTRANSPARENT stage
  22843. if (observable && info) {
  22844. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22845. observable.notifyObservers(info, renderingGroupMask);
  22846. }
  22847. }
  22848. };
  22849. RenderingManager.prototype.reset = function () {
  22850. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22851. var renderingGroup = this._renderingGroups[index];
  22852. if (renderingGroup) {
  22853. renderingGroup.prepare();
  22854. }
  22855. }
  22856. };
  22857. RenderingManager.prototype.dispose = function () {
  22858. this.freeRenderingGroups();
  22859. this._renderingGroups.length = 0;
  22860. };
  22861. /**
  22862. * Clear the info related to rendering groups preventing retention points during dispose.
  22863. */
  22864. RenderingManager.prototype.freeRenderingGroups = function () {
  22865. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22866. var renderingGroup = this._renderingGroups[index];
  22867. if (renderingGroup) {
  22868. renderingGroup.dispose();
  22869. }
  22870. }
  22871. };
  22872. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22873. if (this._renderingGroups[renderingGroupId] === undefined) {
  22874. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22875. }
  22876. };
  22877. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22878. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22879. this._prepareRenderingGroup(renderingGroupId);
  22880. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22881. };
  22882. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22883. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22884. this._prepareRenderingGroup(renderingGroupId);
  22885. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22886. };
  22887. /**
  22888. * @param subMesh The submesh to dispatch
  22889. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22890. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22891. */
  22892. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22893. if (mesh === undefined) {
  22894. mesh = subMesh.getMesh();
  22895. }
  22896. var renderingGroupId = mesh.renderingGroupId || 0;
  22897. this._prepareRenderingGroup(renderingGroupId);
  22898. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22899. };
  22900. /**
  22901. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22902. * This allowed control for front to back rendering or reversly depending of the special needs.
  22903. *
  22904. * @param renderingGroupId The rendering group id corresponding to its index
  22905. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22906. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22907. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22908. */
  22909. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22910. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22911. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22912. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22913. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22914. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22915. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22916. if (this._renderingGroups[renderingGroupId]) {
  22917. var group = this._renderingGroups[renderingGroupId];
  22918. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22919. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22920. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22921. }
  22922. };
  22923. /**
  22924. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22925. *
  22926. * @param renderingGroupId The rendering group id corresponding to its index
  22927. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22928. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22929. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22930. */
  22931. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22932. if (depth === void 0) { depth = true; }
  22933. if (stencil === void 0) { stencil = true; }
  22934. this._autoClearDepthStencil[renderingGroupId] = {
  22935. autoClear: autoClearDepthStencil,
  22936. depth: depth,
  22937. stencil: stencil
  22938. };
  22939. };
  22940. /**
  22941. * The max id used for rendering groups (not included)
  22942. */
  22943. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22944. /**
  22945. * The min id used for rendering groups (included)
  22946. */
  22947. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22948. /**
  22949. * Used to globally prevent autoclearing scenes.
  22950. */
  22951. RenderingManager.AUTOCLEAR = true;
  22952. return RenderingManager;
  22953. }());
  22954. BABYLON.RenderingManager = RenderingManager;
  22955. })(BABYLON || (BABYLON = {}));
  22956. //# sourceMappingURL=babylon.renderingManager.js.map
  22957. var BABYLON;
  22958. (function (BABYLON) {
  22959. var RenderingGroup = /** @class */ (function () {
  22960. /**
  22961. * Creates a new rendering group.
  22962. * @param index The rendering group index
  22963. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22964. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22965. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22966. */
  22967. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22968. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22969. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22970. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22971. this.index = index;
  22972. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22973. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22974. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22975. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22976. this._particleSystems = new BABYLON.SmartArray(256);
  22977. this._spriteManagers = new BABYLON.SmartArray(256);
  22978. this._edgesRenderers = new BABYLON.SmartArray(16);
  22979. this._scene = scene;
  22980. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22981. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22982. this.transparentSortCompareFn = transparentSortCompareFn;
  22983. }
  22984. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22985. /**
  22986. * Set the opaque sort comparison function.
  22987. * If null the sub meshes will be render in the order they were created
  22988. */
  22989. set: function (value) {
  22990. this._opaqueSortCompareFn = value;
  22991. if (value) {
  22992. this._renderOpaque = this.renderOpaqueSorted;
  22993. }
  22994. else {
  22995. this._renderOpaque = RenderingGroup.renderUnsorted;
  22996. }
  22997. },
  22998. enumerable: true,
  22999. configurable: true
  23000. });
  23001. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23002. /**
  23003. * Set the alpha test sort comparison function.
  23004. * If null the sub meshes will be render in the order they were created
  23005. */
  23006. set: function (value) {
  23007. this._alphaTestSortCompareFn = value;
  23008. if (value) {
  23009. this._renderAlphaTest = this.renderAlphaTestSorted;
  23010. }
  23011. else {
  23012. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23013. }
  23014. },
  23015. enumerable: true,
  23016. configurable: true
  23017. });
  23018. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23019. /**
  23020. * Set the transparent sort comparison function.
  23021. * If null the sub meshes will be render in the order they were created
  23022. */
  23023. set: function (value) {
  23024. if (value) {
  23025. this._transparentSortCompareFn = value;
  23026. }
  23027. else {
  23028. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23029. }
  23030. this._renderTransparent = this.renderTransparentSorted;
  23031. },
  23032. enumerable: true,
  23033. configurable: true
  23034. });
  23035. /**
  23036. * Render all the sub meshes contained in the group.
  23037. * @param customRenderFunction Used to override the default render behaviour of the group.
  23038. * @returns true if rendered some submeshes.
  23039. */
  23040. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23041. if (customRenderFunction) {
  23042. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23043. return;
  23044. }
  23045. var engine = this._scene.getEngine();
  23046. // Depth only
  23047. if (this._depthOnlySubMeshes.length !== 0) {
  23048. engine.setColorWrite(false);
  23049. this._renderAlphaTest(this._depthOnlySubMeshes);
  23050. engine.setColorWrite(true);
  23051. }
  23052. // Opaque
  23053. if (this._opaqueSubMeshes.length !== 0) {
  23054. this._renderOpaque(this._opaqueSubMeshes);
  23055. }
  23056. // Alpha test
  23057. if (this._alphaTestSubMeshes.length !== 0) {
  23058. this._renderAlphaTest(this._alphaTestSubMeshes);
  23059. }
  23060. var stencilState = engine.getStencilBuffer();
  23061. engine.setStencilBuffer(false);
  23062. // Sprites
  23063. if (renderSprites) {
  23064. this._renderSprites();
  23065. }
  23066. // Particles
  23067. if (renderParticles) {
  23068. this._renderParticles(activeMeshes);
  23069. }
  23070. if (this.onBeforeTransparentRendering) {
  23071. this.onBeforeTransparentRendering();
  23072. }
  23073. // Transparent
  23074. if (this._transparentSubMeshes.length !== 0) {
  23075. this._renderTransparent(this._transparentSubMeshes);
  23076. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23077. }
  23078. // Set back stencil to false in case it changes before the edge renderer.
  23079. engine.setStencilBuffer(false);
  23080. // Edges
  23081. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23082. this._edgesRenderers.data[edgesRendererIndex].render();
  23083. }
  23084. // Restore Stencil state.
  23085. engine.setStencilBuffer(stencilState);
  23086. };
  23087. /**
  23088. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23089. * @param subMeshes The submeshes to render
  23090. */
  23091. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23092. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23093. };
  23094. /**
  23095. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23096. * @param subMeshes The submeshes to render
  23097. */
  23098. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23099. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23100. };
  23101. /**
  23102. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23103. * @param subMeshes The submeshes to render
  23104. */
  23105. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23106. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23107. };
  23108. /**
  23109. * Renders the submeshes in a specified order.
  23110. * @param subMeshes The submeshes to sort before render
  23111. * @param sortCompareFn The comparison function use to sort
  23112. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23113. * @param transparent Specifies to activate blending if true
  23114. */
  23115. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23116. var subIndex = 0;
  23117. var subMesh;
  23118. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23119. for (; subIndex < subMeshes.length; subIndex++) {
  23120. subMesh = subMeshes.data[subIndex];
  23121. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23122. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23123. }
  23124. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23125. if (sortCompareFn) {
  23126. sortedArray.sort(sortCompareFn);
  23127. }
  23128. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23129. subMesh = sortedArray[subIndex];
  23130. if (transparent) {
  23131. var material = subMesh.getMaterial();
  23132. if (material && material.needDepthPrePass) {
  23133. var engine = material.getScene().getEngine();
  23134. engine.setColorWrite(false);
  23135. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23136. subMesh.render(false);
  23137. engine.setColorWrite(true);
  23138. }
  23139. }
  23140. subMesh.render(transparent);
  23141. }
  23142. };
  23143. /**
  23144. * Renders the submeshes in the order they were dispatched (no sort applied).
  23145. * @param subMeshes The submeshes to render
  23146. */
  23147. RenderingGroup.renderUnsorted = function (subMeshes) {
  23148. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23149. var submesh = subMeshes.data[subIndex];
  23150. submesh.render(false);
  23151. }
  23152. };
  23153. /**
  23154. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23155. * are rendered back to front if in the same alpha index.
  23156. *
  23157. * @param a The first submesh
  23158. * @param b The second submesh
  23159. * @returns The result of the comparison
  23160. */
  23161. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23162. // Alpha index first
  23163. if (a._alphaIndex > b._alphaIndex) {
  23164. return 1;
  23165. }
  23166. if (a._alphaIndex < b._alphaIndex) {
  23167. return -1;
  23168. }
  23169. // Then distance to camera
  23170. return RenderingGroup.backToFrontSortCompare(a, b);
  23171. };
  23172. /**
  23173. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23174. * are rendered back to front.
  23175. *
  23176. * @param a The first submesh
  23177. * @param b The second submesh
  23178. * @returns The result of the comparison
  23179. */
  23180. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23181. // Then distance to camera
  23182. if (a._distanceToCamera < b._distanceToCamera) {
  23183. return 1;
  23184. }
  23185. if (a._distanceToCamera > b._distanceToCamera) {
  23186. return -1;
  23187. }
  23188. return 0;
  23189. };
  23190. /**
  23191. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23192. * are rendered front to back (prevent overdraw).
  23193. *
  23194. * @param a The first submesh
  23195. * @param b The second submesh
  23196. * @returns The result of the comparison
  23197. */
  23198. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23199. // Then distance to camera
  23200. if (a._distanceToCamera < b._distanceToCamera) {
  23201. return -1;
  23202. }
  23203. if (a._distanceToCamera > b._distanceToCamera) {
  23204. return 1;
  23205. }
  23206. return 0;
  23207. };
  23208. /**
  23209. * Resets the different lists of submeshes to prepare a new frame.
  23210. */
  23211. RenderingGroup.prototype.prepare = function () {
  23212. this._opaqueSubMeshes.reset();
  23213. this._transparentSubMeshes.reset();
  23214. this._alphaTestSubMeshes.reset();
  23215. this._depthOnlySubMeshes.reset();
  23216. this._particleSystems.reset();
  23217. this._spriteManagers.reset();
  23218. this._edgesRenderers.reset();
  23219. };
  23220. RenderingGroup.prototype.dispose = function () {
  23221. this._opaqueSubMeshes.dispose();
  23222. this._transparentSubMeshes.dispose();
  23223. this._alphaTestSubMeshes.dispose();
  23224. this._depthOnlySubMeshes.dispose();
  23225. this._particleSystems.dispose();
  23226. this._spriteManagers.dispose();
  23227. this._edgesRenderers.dispose();
  23228. };
  23229. /**
  23230. * Inserts the submesh in its correct queue depending on its material.
  23231. * @param subMesh The submesh to dispatch
  23232. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23233. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23234. */
  23235. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23236. // Get mesh and materials if not provided
  23237. if (mesh === undefined) {
  23238. mesh = subMesh.getMesh();
  23239. }
  23240. if (material === undefined) {
  23241. material = subMesh.getMaterial();
  23242. }
  23243. if (material === null || material === undefined) {
  23244. return;
  23245. }
  23246. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23247. this._transparentSubMeshes.push(subMesh);
  23248. }
  23249. else if (material.needAlphaTesting()) { // Alpha test
  23250. if (material.needDepthPrePass) {
  23251. this._depthOnlySubMeshes.push(subMesh);
  23252. }
  23253. this._alphaTestSubMeshes.push(subMesh);
  23254. }
  23255. else {
  23256. if (material.needDepthPrePass) {
  23257. this._depthOnlySubMeshes.push(subMesh);
  23258. }
  23259. this._opaqueSubMeshes.push(subMesh); // Opaque
  23260. }
  23261. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23262. this._edgesRenderers.push(mesh._edgesRenderer);
  23263. }
  23264. };
  23265. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23266. this._spriteManagers.push(spriteManager);
  23267. };
  23268. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23269. this._particleSystems.push(particleSystem);
  23270. };
  23271. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23272. if (this._particleSystems.length === 0) {
  23273. return;
  23274. }
  23275. // Particles
  23276. var activeCamera = this._scene.activeCamera;
  23277. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23278. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23279. var particleSystem = this._particleSystems.data[particleIndex];
  23280. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23281. continue;
  23282. }
  23283. var emitter = particleSystem.emitter;
  23284. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23285. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23286. }
  23287. }
  23288. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23289. };
  23290. RenderingGroup.prototype._renderSprites = function () {
  23291. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23292. return;
  23293. }
  23294. // Sprites
  23295. var activeCamera = this._scene.activeCamera;
  23296. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23297. for (var id = 0; id < this._spriteManagers.length; id++) {
  23298. var spriteManager = this._spriteManagers.data[id];
  23299. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23300. spriteManager.render();
  23301. }
  23302. }
  23303. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23304. };
  23305. return RenderingGroup;
  23306. }());
  23307. BABYLON.RenderingGroup = RenderingGroup;
  23308. })(BABYLON || (BABYLON = {}));
  23309. //# sourceMappingURL=babylon.renderingGroup.js.map
  23310. var BABYLON;
  23311. (function (BABYLON) {
  23312. /**
  23313. * Groups all the scene component constants in one place to ease maintenance.
  23314. * @hidden
  23315. */
  23316. var SceneComponentConstants = /** @class */ (function () {
  23317. function SceneComponentConstants() {
  23318. }
  23319. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23320. SceneComponentConstants.NAME_LAYER = "Layer";
  23321. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23322. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23323. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23324. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23325. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23326. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23327. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23328. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23329. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23330. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23331. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23332. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23333. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23334. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23335. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23336. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23337. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23338. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23339. return SceneComponentConstants;
  23340. }());
  23341. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23342. /**
  23343. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23344. * @hidden
  23345. */
  23346. var Stage = /** @class */ (function (_super) {
  23347. __extends(Stage, _super);
  23348. /**
  23349. * Hide ctor from the rest of the world.
  23350. * @param items The items to add.
  23351. */
  23352. function Stage(items) {
  23353. return _super.apply(this, items) || this;
  23354. }
  23355. /**
  23356. * Creates a new Stage.
  23357. * @returns A new instance of a Stage
  23358. */
  23359. Stage.Create = function () {
  23360. return Object.create(Stage.prototype);
  23361. };
  23362. /**
  23363. * Registers a step in an ordered way in the targeted stage.
  23364. * @param index Defines the position to register the step in
  23365. * @param component Defines the component attached to the step
  23366. * @param action Defines the action to launch during the step
  23367. */
  23368. Stage.prototype.registerStep = function (index, component, action) {
  23369. var i = 0;
  23370. var maxIndex = Number.MAX_VALUE;
  23371. for (; i < this.length && i < maxIndex; i++) {
  23372. var step = this[i];
  23373. maxIndex = step.index;
  23374. }
  23375. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23376. };
  23377. /**
  23378. * Clears all the steps from the stage.
  23379. */
  23380. Stage.prototype.clear = function () {
  23381. this.length = 0;
  23382. };
  23383. return Stage;
  23384. }(Array));
  23385. BABYLON.Stage = Stage;
  23386. })(BABYLON || (BABYLON = {}));
  23387. //# sourceMappingURL=babylon.sceneComponent.js.map
  23388. var BABYLON;
  23389. (function (BABYLON) {
  23390. /**
  23391. * Base class of the scene acting as a container for the different elements composing a scene.
  23392. * This class is dynamically extended by the different components of the scene increasing
  23393. * flexibility and reducing coupling
  23394. */
  23395. var AbstractScene = /** @class */ (function () {
  23396. function AbstractScene() {
  23397. /** All of the cameras added to this scene
  23398. * @see http://doc.babylonjs.com/babylon101/cameras
  23399. */
  23400. this.cameras = new Array();
  23401. /**
  23402. * All of the lights added to this scene
  23403. * @see http://doc.babylonjs.com/babylon101/lights
  23404. */
  23405. this.lights = new Array();
  23406. /**
  23407. * All of the (abstract) meshes added to this scene
  23408. */
  23409. this.meshes = new Array();
  23410. /**
  23411. * The list of skeletons added to the scene
  23412. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23413. */
  23414. this.skeletons = new Array();
  23415. /**
  23416. * All of the particle systems added to this scene
  23417. * @see http://doc.babylonjs.com/babylon101/particles
  23418. */
  23419. this.particleSystems = new Array();
  23420. /**
  23421. * Gets a list of Animations associated with the scene
  23422. */
  23423. this.animations = [];
  23424. /**
  23425. * All of the animation groups added to this scene
  23426. * @see http://doc.babylonjs.com/how_to/group
  23427. */
  23428. this.animationGroups = new Array();
  23429. /**
  23430. * All of the multi-materials added to this scene
  23431. * @see http://doc.babylonjs.com/how_to/multi_materials
  23432. */
  23433. this.multiMaterials = new Array();
  23434. /**
  23435. * All of the materials added to this scene
  23436. * @see http://doc.babylonjs.com/babylon101/materials
  23437. */
  23438. this.materials = new Array();
  23439. /**
  23440. * The list of morph target managers added to the scene
  23441. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23442. */
  23443. this.morphTargetManagers = new Array();
  23444. /**
  23445. * The list of geometries used in the scene.
  23446. */
  23447. this.geometries = new Array();
  23448. /**
  23449. * All of the tranform nodes added to this scene
  23450. * @see http://doc.babylonjs.com/how_to/transformnode
  23451. */
  23452. this.transformNodes = new Array();
  23453. /**
  23454. * ActionManagers available on the scene.
  23455. */
  23456. this.actionManagers = new Array();
  23457. /**
  23458. * Sounds to keep.
  23459. */
  23460. this.sounds = new Array();
  23461. /**
  23462. * Textures to keep.
  23463. */
  23464. this.textures = new Array();
  23465. }
  23466. /**
  23467. * Adds a parser in the list of available ones
  23468. * @param name Defines the name of the parser
  23469. * @param parser Defines the parser to add
  23470. */
  23471. AbstractScene.AddParser = function (name, parser) {
  23472. this._BabylonFileParsers[name] = parser;
  23473. };
  23474. /**
  23475. * Gets a general parser from the list of avaialble ones
  23476. * @param name Defines the name of the parser
  23477. * @returns the requested parser or null
  23478. */
  23479. AbstractScene.GetParser = function (name) {
  23480. if (this._BabylonFileParsers[name]) {
  23481. return this._BabylonFileParsers[name];
  23482. }
  23483. return null;
  23484. };
  23485. /**
  23486. * Adds n individual parser in the list of available ones
  23487. * @param name Defines the name of the parser
  23488. * @param parser Defines the parser to add
  23489. */
  23490. AbstractScene.AddIndividualParser = function (name, parser) {
  23491. this._IndividualBabylonFileParsers[name] = parser;
  23492. };
  23493. /**
  23494. * Gets an individual parser from the list of avaialble ones
  23495. * @param name Defines the name of the parser
  23496. * @returns the requested parser or null
  23497. */
  23498. AbstractScene.GetIndividualParser = function (name) {
  23499. if (this._IndividualBabylonFileParsers[name]) {
  23500. return this._IndividualBabylonFileParsers[name];
  23501. }
  23502. return null;
  23503. };
  23504. /**
  23505. * Parser json data and populate both a scene and its associated container object
  23506. * @param jsonData Defines the data to parse
  23507. * @param scene Defines the scene to parse the data for
  23508. * @param container Defines the container attached to the parsing sequence
  23509. * @param rootUrl Defines the root url of the data
  23510. */
  23511. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23512. for (var parserName in this._BabylonFileParsers) {
  23513. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23514. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23515. }
  23516. }
  23517. };
  23518. /**
  23519. * Stores the list of available parsers in the application.
  23520. */
  23521. AbstractScene._BabylonFileParsers = {};
  23522. /**
  23523. * Stores the list of available individual parsers in the application.
  23524. */
  23525. AbstractScene._IndividualBabylonFileParsers = {};
  23526. return AbstractScene;
  23527. }());
  23528. BABYLON.AbstractScene = AbstractScene;
  23529. })(BABYLON || (BABYLON = {}));
  23530. //# sourceMappingURL=babylon.abstractScene.js.map
  23531. var BABYLON;
  23532. (function (BABYLON) {
  23533. /** @hidden */
  23534. var ClickInfo = /** @class */ (function () {
  23535. function ClickInfo() {
  23536. this._singleClick = false;
  23537. this._doubleClick = false;
  23538. this._hasSwiped = false;
  23539. this._ignore = false;
  23540. }
  23541. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23542. get: function () {
  23543. return this._singleClick;
  23544. },
  23545. set: function (b) {
  23546. this._singleClick = b;
  23547. },
  23548. enumerable: true,
  23549. configurable: true
  23550. });
  23551. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23552. get: function () {
  23553. return this._doubleClick;
  23554. },
  23555. set: function (b) {
  23556. this._doubleClick = b;
  23557. },
  23558. enumerable: true,
  23559. configurable: true
  23560. });
  23561. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23562. get: function () {
  23563. return this._hasSwiped;
  23564. },
  23565. set: function (b) {
  23566. this._hasSwiped = b;
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23572. get: function () {
  23573. return this._ignore;
  23574. },
  23575. set: function (b) {
  23576. this._ignore = b;
  23577. },
  23578. enumerable: true,
  23579. configurable: true
  23580. });
  23581. return ClickInfo;
  23582. }());
  23583. /**
  23584. * This class is used by the onRenderingGroupObservable
  23585. */
  23586. var RenderingGroupInfo = /** @class */ (function () {
  23587. function RenderingGroupInfo() {
  23588. }
  23589. /**
  23590. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23591. * This stage will be fired no matter what
  23592. */
  23593. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23594. /**
  23595. * Called before opaque object are rendered.
  23596. * This stage will be fired only if there's 3D Opaque content to render
  23597. */
  23598. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23599. /**
  23600. * Called after the opaque objects are rendered and before the transparent ones
  23601. * This stage will be fired only if there's 3D transparent content to render
  23602. */
  23603. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23604. /**
  23605. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23606. * This stage will be fired no matter what
  23607. */
  23608. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23609. return RenderingGroupInfo;
  23610. }());
  23611. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23612. /**
  23613. * Represents a scene to be rendered by the engine.
  23614. * @see http://doc.babylonjs.com/features/scene
  23615. */
  23616. var Scene = /** @class */ (function (_super) {
  23617. __extends(Scene, _super);
  23618. /**
  23619. * Creates a new Scene
  23620. * @param engine defines the engine to use to render this scene
  23621. */
  23622. function Scene(engine) {
  23623. var _this = _super.call(this) || this;
  23624. // Members
  23625. /**
  23626. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23627. */
  23628. _this.autoClear = true;
  23629. /**
  23630. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23631. */
  23632. _this.autoClearDepthAndStencil = true;
  23633. /**
  23634. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23635. */
  23636. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23637. /**
  23638. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23639. */
  23640. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23641. _this._forceWireframe = false;
  23642. _this._forcePointsCloud = false;
  23643. /**
  23644. * Gets or sets a boolean indicating if animations are enabled
  23645. */
  23646. _this.animationsEnabled = true;
  23647. _this._animationPropertiesOverride = null;
  23648. /**
  23649. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23650. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23651. */
  23652. _this.useConstantAnimationDeltaTime = false;
  23653. /**
  23654. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23655. * Please note that it requires to run a ray cast through the scene on every frame
  23656. */
  23657. _this.constantlyUpdateMeshUnderPointer = false;
  23658. /**
  23659. * Defines the HTML cursor to use when hovering over interactive elements
  23660. */
  23661. _this.hoverCursor = "pointer";
  23662. /**
  23663. * Defines the HTML default cursor to use (empty by default)
  23664. */
  23665. _this.defaultCursor = "";
  23666. /**
  23667. * This is used to call preventDefault() on pointer down
  23668. * in order to block unwanted artifacts like system double clicks
  23669. */
  23670. _this.preventDefaultOnPointerDown = true;
  23671. // Metadata
  23672. /**
  23673. * Gets or sets user defined metadata
  23674. */
  23675. _this.metadata = null;
  23676. /**
  23677. * Use this array to add regular expressions used to disable offline support for specific urls
  23678. */
  23679. _this.disableOfflineSupportExceptionRules = new Array();
  23680. /**
  23681. * An event triggered when the scene is disposed.
  23682. */
  23683. _this.onDisposeObservable = new BABYLON.Observable();
  23684. _this._onDisposeObserver = null;
  23685. /**
  23686. * An event triggered before rendering the scene (right after animations and physics)
  23687. */
  23688. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23689. _this._onBeforeRenderObserver = null;
  23690. /**
  23691. * An event triggered after rendering the scene
  23692. */
  23693. _this.onAfterRenderObservable = new BABYLON.Observable();
  23694. _this._onAfterRenderObserver = null;
  23695. /**
  23696. * An event triggered before animating the scene
  23697. */
  23698. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23699. /**
  23700. * An event triggered after animations processing
  23701. */
  23702. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23703. /**
  23704. * An event triggered before draw calls are ready to be sent
  23705. */
  23706. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered after draw calls have been sent
  23709. */
  23710. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered when physic simulation is about to be run
  23713. */
  23714. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23715. /**
  23716. * An event triggered when physic simulation has been done
  23717. */
  23718. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23719. /**
  23720. * An event triggered when the scene is ready
  23721. */
  23722. _this.onReadyObservable = new BABYLON.Observable();
  23723. /**
  23724. * An event triggered before rendering a camera
  23725. */
  23726. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23727. _this._onBeforeCameraRenderObserver = null;
  23728. /**
  23729. * An event triggered after rendering a camera
  23730. */
  23731. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23732. _this._onAfterCameraRenderObserver = null;
  23733. /**
  23734. * An event triggered when active meshes evaluation is about to start
  23735. */
  23736. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23737. /**
  23738. * An event triggered when active meshes evaluation is done
  23739. */
  23740. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23741. /**
  23742. * An event triggered when particles rendering is about to start
  23743. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23744. */
  23745. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23746. /**
  23747. * An event triggered when particles rendering is done
  23748. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23749. */
  23750. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23751. /**
  23752. * An event triggered when sprites rendering is about to start
  23753. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23754. */
  23755. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered when sprites rendering is done
  23758. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23759. */
  23760. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23761. /**
  23762. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23763. */
  23764. _this.onDataLoadedObservable = new BABYLON.Observable();
  23765. /**
  23766. * An event triggered when a camera is created
  23767. */
  23768. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23769. /**
  23770. * An event triggered when a camera is removed
  23771. */
  23772. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23773. /**
  23774. * An event triggered when a light is created
  23775. */
  23776. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23777. /**
  23778. * An event triggered when a light is removed
  23779. */
  23780. _this.onLightRemovedObservable = new BABYLON.Observable();
  23781. /**
  23782. * An event triggered when a geometry is created
  23783. */
  23784. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23785. /**
  23786. * An event triggered when a geometry is removed
  23787. */
  23788. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23789. /**
  23790. * An event triggered when a transform node is created
  23791. */
  23792. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23793. /**
  23794. * An event triggered when a transform node is removed
  23795. */
  23796. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23797. /**
  23798. * An event triggered when a mesh is created
  23799. */
  23800. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23801. /**
  23802. * An event triggered when a mesh is removed
  23803. */
  23804. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23805. /**
  23806. * An event triggered when render targets are about to be rendered
  23807. * Can happen multiple times per frame.
  23808. */
  23809. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23810. /**
  23811. * An event triggered when render targets were rendered.
  23812. * Can happen multiple times per frame.
  23813. */
  23814. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23815. /**
  23816. * An event triggered before calculating deterministic simulation step
  23817. */
  23818. _this.onBeforeStepObservable = new BABYLON.Observable();
  23819. /**
  23820. * An event triggered after calculating deterministic simulation step
  23821. */
  23822. _this.onAfterStepObservable = new BABYLON.Observable();
  23823. /**
  23824. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23825. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23826. * 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)
  23827. */
  23828. _this.onRenderingGroupObservable = new BABYLON.Observable();
  23829. // Animations
  23830. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23831. /**
  23832. * 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).
  23833. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23834. */
  23835. _this.onPrePointerObservable = new BABYLON.Observable();
  23836. /**
  23837. * Observable event triggered each time an input event is received from the rendering canvas
  23838. */
  23839. _this.onPointerObservable = new BABYLON.Observable();
  23840. _this._meshPickProceed = false;
  23841. _this._currentPickResult = null;
  23842. _this._previousPickResult = null;
  23843. _this._totalPointersPressed = 0;
  23844. _this._doubleClickOccured = false;
  23845. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23846. _this.cameraToUseForPointers = null;
  23847. _this._pointerX = 0;
  23848. _this._pointerY = 0;
  23849. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23850. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23851. _this._startingPointerTime = 0;
  23852. _this._previousStartingPointerTime = 0;
  23853. _this._pointerCaptures = {};
  23854. // Deterministic lockstep
  23855. _this._timeAccumulator = 0;
  23856. _this._currentStepId = 0;
  23857. _this._currentInternalStep = 0;
  23858. // Keyboard
  23859. /**
  23860. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23861. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23862. */
  23863. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23864. /**
  23865. * Observable event triggered each time an keyboard event is received from the hosting window
  23866. */
  23867. _this.onKeyboardObservable = new BABYLON.Observable();
  23868. // Coordinates system
  23869. _this._useRightHandedSystem = false;
  23870. // Fog
  23871. _this._fogEnabled = true;
  23872. _this._fogMode = Scene.FOGMODE_NONE;
  23873. /**
  23874. * Gets or sets the fog color to use
  23875. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23876. */
  23877. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23878. /**
  23879. * Gets or sets the fog density to use
  23880. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23881. */
  23882. _this.fogDensity = 0.1;
  23883. /**
  23884. * Gets or sets the fog start distance to use
  23885. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23886. */
  23887. _this.fogStart = 0;
  23888. /**
  23889. * Gets or sets the fog end distance to use
  23890. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23891. */
  23892. _this.fogEnd = 1000.0;
  23893. // Lights
  23894. _this._shadowsEnabled = true;
  23895. _this._lightsEnabled = true;
  23896. /** All of the active cameras added to this scene. */
  23897. _this.activeCameras = new Array();
  23898. // Textures
  23899. _this._texturesEnabled = true;
  23900. // Particles
  23901. /**
  23902. * Gets or sets a boolean indicating if particles are enabled on this scene
  23903. */
  23904. _this.particlesEnabled = true;
  23905. // Sprites
  23906. /**
  23907. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23908. */
  23909. _this.spritesEnabled = true;
  23910. /**
  23911. * All of the sprite managers added to this scene
  23912. * @see http://doc.babylonjs.com/babylon101/sprites
  23913. */
  23914. _this.spriteManagers = new Array();
  23915. // Skeletons
  23916. _this._skeletonsEnabled = true;
  23917. // Lens flares
  23918. /**
  23919. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23920. */
  23921. _this.lensFlaresEnabled = true;
  23922. // Collisions
  23923. /**
  23924. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23925. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23926. */
  23927. _this.collisionsEnabled = true;
  23928. /**
  23929. * Defines the gravity applied to this scene (used only for collisions)
  23930. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23931. */
  23932. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23933. // Postprocesses
  23934. /**
  23935. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23936. */
  23937. _this.postProcessesEnabled = true;
  23938. /**
  23939. * The list of postprocesses added to the scene
  23940. */
  23941. _this.postProcesses = new Array();
  23942. // Customs render targets
  23943. /**
  23944. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23945. */
  23946. _this.renderTargetsEnabled = true;
  23947. /**
  23948. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23949. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23950. */
  23951. _this.dumpNextRenderTargets = false;
  23952. /**
  23953. * The list of user defined render targets added to the scene
  23954. */
  23955. _this.customRenderTargets = new Array();
  23956. /**
  23957. * Gets the list of meshes imported to the scene through SceneLoader
  23958. */
  23959. _this.importedMeshesFiles = new Array();
  23960. // Probes
  23961. /**
  23962. * Gets or sets a boolean indicating if probes are enabled on this scene
  23963. */
  23964. _this.probesEnabled = true;
  23965. /**
  23966. * The list of reflection probes added to the scene
  23967. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23968. */
  23969. _this.reflectionProbes = new Array();
  23970. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23971. // Procedural textures
  23972. /**
  23973. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23974. */
  23975. _this.proceduralTexturesEnabled = true;
  23976. /**
  23977. * The list of procedural textures added to the scene
  23978. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23979. */
  23980. _this.proceduralTextures = new Array();
  23981. /**
  23982. * The list of sound tracks added to the scene
  23983. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23984. */
  23985. _this.soundTracks = new Array();
  23986. _this._audioEnabled = true;
  23987. _this._headphone = false;
  23988. // Performance counters
  23989. _this._totalVertices = new BABYLON.PerfCounter();
  23990. /** @hidden */
  23991. _this._activeIndices = new BABYLON.PerfCounter();
  23992. /** @hidden */
  23993. _this._activeParticles = new BABYLON.PerfCounter();
  23994. /** @hidden */
  23995. _this._activeBones = new BABYLON.PerfCounter();
  23996. _this._animationTime = 0;
  23997. /**
  23998. * Gets or sets a general scale for animation speed
  23999. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24000. */
  24001. _this.animationTimeScale = 1;
  24002. _this._renderId = 0;
  24003. _this._executeWhenReadyTimeoutId = -1;
  24004. _this._intermediateRendering = false;
  24005. _this._viewUpdateFlag = -1;
  24006. _this._projectionUpdateFlag = -1;
  24007. _this._alternateViewUpdateFlag = -1;
  24008. _this._alternateProjectionUpdateFlag = -1;
  24009. /** @hidden */
  24010. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24011. _this._activeRequests = new Array();
  24012. _this._pendingData = new Array();
  24013. _this._isDisposed = false;
  24014. /**
  24015. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24016. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24017. */
  24018. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24019. _this._activeMeshes = new BABYLON.SmartArray(256);
  24020. _this._processedMaterials = new BABYLON.SmartArray(256);
  24021. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24022. /** @hidden */
  24023. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24024. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24025. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24026. /** @hidden */
  24027. _this._activeAnimatables = new Array();
  24028. _this._transformMatrix = BABYLON.Matrix.Zero();
  24029. _this._useAlternateCameraConfiguration = false;
  24030. _this._alternateRendering = false;
  24031. /**
  24032. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24033. * This is useful if there are more lights that the maximum simulteanous authorized
  24034. */
  24035. _this.requireLightSorting = false;
  24036. _this._depthRenderer = {};
  24037. /**
  24038. * Backing store of defined scene components.
  24039. */
  24040. _this._components = [];
  24041. /**
  24042. * Backing store of defined scene components.
  24043. */
  24044. _this._serializableComponents = [];
  24045. /**
  24046. * List of components to register on the next registration step.
  24047. */
  24048. _this._transientComponents = [];
  24049. /**
  24050. * Defines the actions happening before camera updates.
  24051. */
  24052. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24053. /**
  24054. * Defines the actions happening during the per mesh ready checks.
  24055. */
  24056. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24057. /**
  24058. * Defines the actions happening before evaluate active mesh checks.
  24059. */
  24060. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24061. /**
  24062. * Defines the actions happening during the evaluate sub mesh checks.
  24063. */
  24064. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24065. /**
  24066. * Defines the actions happening during the active mesh stage.
  24067. */
  24068. _this._activeMeshStage = BABYLON.Stage.Create();
  24069. /**
  24070. * Defines the actions happening during the per camera render target step.
  24071. */
  24072. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24073. /**
  24074. * Defines the actions happening just before the active camera is drawing.
  24075. */
  24076. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24077. /**
  24078. * Defines the actions happening just before a rendering group is drawing.
  24079. */
  24080. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24081. /**
  24082. * Defines the actions happening just after a rendering group has been drawn.
  24083. */
  24084. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24085. /**
  24086. * Defines the actions happening just after the active camera has been drawn.
  24087. */
  24088. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24089. _this._activeMeshesFrozen = false;
  24090. /** @hidden */
  24091. _this._allowPostProcessClear = true;
  24092. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24093. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24094. _this._engine.scenes.push(_this);
  24095. _this._uid = null;
  24096. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24097. if (BABYLON.PostProcessManager) {
  24098. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24099. }
  24100. if (BABYLON.OutlineRenderer) {
  24101. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24102. }
  24103. if (BABYLON.Tools.IsWindowObjectExist()) {
  24104. _this.attachControl();
  24105. }
  24106. //simplification queue
  24107. if (BABYLON.SimplificationQueue) {
  24108. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24109. }
  24110. //collision coordinator initialization. For now legacy per default.
  24111. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24112. // Uniform Buffer
  24113. _this._createUbo();
  24114. // Default Image processing definition
  24115. if (BABYLON.ImageProcessingConfiguration) {
  24116. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24117. }
  24118. return _this;
  24119. }
  24120. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24121. /** The fog is deactivated */
  24122. get: function () {
  24123. return Scene._FOGMODE_NONE;
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24129. /** The fog density is following an exponential function */
  24130. get: function () {
  24131. return Scene._FOGMODE_EXP;
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24137. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24138. get: function () {
  24139. return Scene._FOGMODE_EXP2;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24145. /** The fog density is following a linear function. */
  24146. get: function () {
  24147. return Scene._FOGMODE_LINEAR;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24153. /**
  24154. * Texture used in all pbr material as the reflection texture.
  24155. * As in the majority of the scene they are the same (exception for multi room and so on),
  24156. * this is easier to reference from here than from all the materials.
  24157. */
  24158. get: function () {
  24159. return this._environmentTexture;
  24160. },
  24161. /**
  24162. * Texture used in all pbr material as the reflection texture.
  24163. * As in the majority of the scene they are the same (exception for multi room and so on),
  24164. * this is easier to set here than in all the materials.
  24165. */
  24166. set: function (value) {
  24167. if (this._environmentTexture === value) {
  24168. return;
  24169. }
  24170. this._environmentTexture = value;
  24171. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24177. /**
  24178. * Default image processing configuration used either in the rendering
  24179. * Forward main pass or through the imageProcessingPostProcess if present.
  24180. * As in the majority of the scene they are the same (exception for multi camera),
  24181. * this is easier to reference from here than from all the materials and post process.
  24182. *
  24183. * No setter as we it is a shared configuration, you can set the values instead.
  24184. */
  24185. get: function () {
  24186. return this._imageProcessingConfiguration;
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24192. get: function () {
  24193. return this._forceWireframe;
  24194. },
  24195. /**
  24196. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24197. */
  24198. set: function (value) {
  24199. if (this._forceWireframe === value) {
  24200. return;
  24201. }
  24202. this._forceWireframe = value;
  24203. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24209. get: function () {
  24210. return this._forcePointsCloud;
  24211. },
  24212. /**
  24213. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24214. */
  24215. set: function (value) {
  24216. if (this._forcePointsCloud === value) {
  24217. return;
  24218. }
  24219. this._forcePointsCloud = value;
  24220. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24226. /**
  24227. * Gets or sets the animation properties override
  24228. */
  24229. get: function () {
  24230. return this._animationPropertiesOverride;
  24231. },
  24232. set: function (value) {
  24233. this._animationPropertiesOverride = value;
  24234. },
  24235. enumerable: true,
  24236. configurable: true
  24237. });
  24238. Object.defineProperty(Scene.prototype, "onDispose", {
  24239. /** Sets a function to be executed when this scene is disposed. */
  24240. set: function (callback) {
  24241. if (this._onDisposeObserver) {
  24242. this.onDisposeObservable.remove(this._onDisposeObserver);
  24243. }
  24244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. Object.defineProperty(Scene.prototype, "beforeRender", {
  24250. /** Sets a function to be executed before rendering this scene */
  24251. set: function (callback) {
  24252. if (this._onBeforeRenderObserver) {
  24253. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24254. }
  24255. if (callback) {
  24256. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24257. }
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Scene.prototype, "afterRender", {
  24263. /** Sets a function to be executed after rendering this scene */
  24264. set: function (callback) {
  24265. if (this._onAfterRenderObserver) {
  24266. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24267. }
  24268. if (callback) {
  24269. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24270. }
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24276. /** Sets a function to be executed before rendering a camera*/
  24277. set: function (callback) {
  24278. if (this._onBeforeCameraRenderObserver) {
  24279. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24280. }
  24281. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24287. /** Sets a function to be executed after rendering a camera*/
  24288. set: function (callback) {
  24289. if (this._onAfterCameraRenderObserver) {
  24290. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24291. }
  24292. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24298. /**
  24299. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24300. */
  24301. get: function () {
  24302. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24303. },
  24304. enumerable: true,
  24305. configurable: true
  24306. });
  24307. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24308. get: function () {
  24309. return this._useRightHandedSystem;
  24310. },
  24311. /**
  24312. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24313. */
  24314. set: function (value) {
  24315. if (this._useRightHandedSystem === value) {
  24316. return;
  24317. }
  24318. this._useRightHandedSystem = value;
  24319. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24320. },
  24321. enumerable: true,
  24322. configurable: true
  24323. });
  24324. /**
  24325. * Sets the step Id used by deterministic lock step
  24326. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24327. * @param newStepId defines the step Id
  24328. */
  24329. Scene.prototype.setStepId = function (newStepId) {
  24330. this._currentStepId = newStepId;
  24331. };
  24332. ;
  24333. /**
  24334. * Gets the step Id used by deterministic lock step
  24335. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24336. * @returns the step Id
  24337. */
  24338. Scene.prototype.getStepId = function () {
  24339. return this._currentStepId;
  24340. };
  24341. ;
  24342. /**
  24343. * Gets the internal step used by deterministic lock step
  24344. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24345. * @returns the internal step
  24346. */
  24347. Scene.prototype.getInternalStep = function () {
  24348. return this._currentInternalStep;
  24349. };
  24350. ;
  24351. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24352. get: function () {
  24353. return this._fogEnabled;
  24354. },
  24355. /**
  24356. * Gets or sets a boolean indicating if fog is enabled on this scene
  24357. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24358. */
  24359. set: function (value) {
  24360. if (this._fogEnabled === value) {
  24361. return;
  24362. }
  24363. this._fogEnabled = value;
  24364. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(Scene.prototype, "fogMode", {
  24370. get: function () {
  24371. return this._fogMode;
  24372. },
  24373. /**
  24374. * Gets or sets the fog mode to use
  24375. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24376. */
  24377. set: function (value) {
  24378. if (this._fogMode === value) {
  24379. return;
  24380. }
  24381. this._fogMode = value;
  24382. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24388. get: function () {
  24389. return this._shadowsEnabled;
  24390. },
  24391. /**
  24392. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24393. */
  24394. set: function (value) {
  24395. if (this._shadowsEnabled === value) {
  24396. return;
  24397. }
  24398. this._shadowsEnabled = value;
  24399. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24405. get: function () {
  24406. return this._lightsEnabled;
  24407. },
  24408. /**
  24409. * Gets or sets a boolean indicating if lights are enabled on this scene
  24410. */
  24411. set: function (value) {
  24412. if (this._lightsEnabled === value) {
  24413. return;
  24414. }
  24415. this._lightsEnabled = value;
  24416. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24417. },
  24418. enumerable: true,
  24419. configurable: true
  24420. });
  24421. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24422. /** The default material used on meshes when no material is affected */
  24423. get: function () {
  24424. if (!this._defaultMaterial) {
  24425. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24426. }
  24427. return this._defaultMaterial;
  24428. },
  24429. /** The default material used on meshes when no material is affected */
  24430. set: function (value) {
  24431. this._defaultMaterial = value;
  24432. },
  24433. enumerable: true,
  24434. configurable: true
  24435. });
  24436. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24437. get: function () {
  24438. return this._texturesEnabled;
  24439. },
  24440. /**
  24441. * Gets or sets a boolean indicating if textures are enabled on this scene
  24442. */
  24443. set: function (value) {
  24444. if (this._texturesEnabled === value) {
  24445. return;
  24446. }
  24447. this._texturesEnabled = value;
  24448. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24454. get: function () {
  24455. return this._skeletonsEnabled;
  24456. },
  24457. /**
  24458. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24459. */
  24460. set: function (value) {
  24461. if (this._skeletonsEnabled === value) {
  24462. return;
  24463. }
  24464. this._skeletonsEnabled = value;
  24465. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24471. /**
  24472. * Gets the postprocess render pipeline manager
  24473. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24474. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24475. */
  24476. get: function () {
  24477. if (!this._postProcessRenderPipelineManager) {
  24478. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24479. }
  24480. return this._postProcessRenderPipelineManager;
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24486. /**
  24487. * Gets the main soundtrack associated with the scene
  24488. */
  24489. get: function () {
  24490. if (!this._mainSoundTrack) {
  24491. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24492. }
  24493. return this._mainSoundTrack;
  24494. },
  24495. enumerable: true,
  24496. configurable: true
  24497. });
  24498. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24499. /** @hidden */
  24500. get: function () {
  24501. return this._alternateRendering;
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24507. /**
  24508. * Gets the list of frustum planes (built from the active camera)
  24509. */
  24510. get: function () {
  24511. return this._frustumPlanes;
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24517. /**
  24518. * Gets the current geometry buffer associated to the scene.
  24519. */
  24520. get: function () {
  24521. return this._geometryBufferRenderer;
  24522. },
  24523. /**
  24524. * Sets the current geometry buffer for the scene.
  24525. */
  24526. set: function (geometryBufferRenderer) {
  24527. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24528. this._geometryBufferRenderer = geometryBufferRenderer;
  24529. }
  24530. },
  24531. enumerable: true,
  24532. configurable: true
  24533. });
  24534. /**
  24535. * Registers the transient components if needed.
  24536. */
  24537. Scene.prototype._registerTransientComponents = function () {
  24538. // Register components that have been associated lately to the scene.
  24539. if (this._transientComponents.length > 0) {
  24540. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24541. var component = _a[_i];
  24542. component.register();
  24543. }
  24544. this._transientComponents = [];
  24545. }
  24546. };
  24547. /**
  24548. * Add a component to the scene.
  24549. * Note that the ccomponent could be registered on th next frame if this is called after
  24550. * the register component stage.
  24551. * @param component Defines the component to add to the scene
  24552. */
  24553. Scene.prototype._addComponent = function (component) {
  24554. this._components.push(component);
  24555. this._transientComponents.push(component);
  24556. var serializableComponent = component;
  24557. if (serializableComponent.addFromContainer) {
  24558. this._serializableComponents.push(serializableComponent);
  24559. }
  24560. };
  24561. /**
  24562. * Gets a component from the scene.
  24563. * @param name defines the name of the component to retrieve
  24564. * @returns the component or null if not present
  24565. */
  24566. Scene.prototype._getComponent = function (name) {
  24567. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24568. var component = _a[_i];
  24569. if (component.name === name) {
  24570. return component;
  24571. }
  24572. }
  24573. return null;
  24574. };
  24575. Object.defineProperty(Scene.prototype, "debugLayer", {
  24576. /**
  24577. * Gets the debug layer (aka Inspector) associated with the scene
  24578. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24579. */
  24580. get: function () {
  24581. if (!this._debugLayer) {
  24582. this._debugLayer = new BABYLON.DebugLayer(this);
  24583. }
  24584. return this._debugLayer;
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24590. /**
  24591. * Gets a boolean indicating if collisions are processed on a web worker
  24592. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24593. */
  24594. get: function () {
  24595. return this._workerCollisions;
  24596. },
  24597. set: function (enabled) {
  24598. if (!BABYLON.CollisionCoordinatorLegacy) {
  24599. return;
  24600. }
  24601. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24602. this._workerCollisions = enabled;
  24603. if (this.collisionCoordinator) {
  24604. this.collisionCoordinator.destroy();
  24605. }
  24606. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24607. this.collisionCoordinator.init(this);
  24608. },
  24609. enumerable: true,
  24610. configurable: true
  24611. });
  24612. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24613. /**
  24614. * Gets the octree used to boost mesh selection (picking)
  24615. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24616. */
  24617. get: function () {
  24618. return this._selectionOctree;
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24624. /**
  24625. * Gets the mesh that is currently under the pointer
  24626. */
  24627. get: function () {
  24628. return this._pointerOverMesh;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Scene.prototype, "pointerX", {
  24634. /**
  24635. * Gets the current on-screen X position of the pointer
  24636. */
  24637. get: function () {
  24638. return this._pointerX;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(Scene.prototype, "pointerY", {
  24644. /**
  24645. * Gets the current on-screen Y position of the pointer
  24646. */
  24647. get: function () {
  24648. return this._pointerY;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. /**
  24654. * Gets the cached material (ie. the latest rendered one)
  24655. * @returns the cached material
  24656. */
  24657. Scene.prototype.getCachedMaterial = function () {
  24658. return this._cachedMaterial;
  24659. };
  24660. /**
  24661. * Gets the cached effect (ie. the latest rendered one)
  24662. * @returns the cached effect
  24663. */
  24664. Scene.prototype.getCachedEffect = function () {
  24665. return this._cachedEffect;
  24666. };
  24667. /**
  24668. * Gets the cached visibility state (ie. the latest rendered one)
  24669. * @returns the cached visibility state
  24670. */
  24671. Scene.prototype.getCachedVisibility = function () {
  24672. return this._cachedVisibility;
  24673. };
  24674. /**
  24675. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24676. * @param material defines the current material
  24677. * @param effect defines the current effect
  24678. * @param visibility defines the current visibility state
  24679. * @returns true if one parameter is not cached
  24680. */
  24681. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24682. if (visibility === void 0) { visibility = 1; }
  24683. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24684. };
  24685. /**
  24686. * Gets the outline renderer associated with the scene
  24687. * @returns a OutlineRenderer
  24688. */
  24689. Scene.prototype.getOutlineRenderer = function () {
  24690. return this._outlineRenderer;
  24691. };
  24692. /**
  24693. * Gets the engine associated with the scene
  24694. * @returns an Engine
  24695. */
  24696. Scene.prototype.getEngine = function () {
  24697. return this._engine;
  24698. };
  24699. /**
  24700. * Gets the total number of vertices rendered per frame
  24701. * @returns the total number of vertices rendered per frame
  24702. */
  24703. Scene.prototype.getTotalVertices = function () {
  24704. return this._totalVertices.current;
  24705. };
  24706. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24707. /**
  24708. * Gets the performance counter for total vertices
  24709. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24710. */
  24711. get: function () {
  24712. return this._totalVertices;
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. /**
  24718. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24719. * @returns the total number of active indices rendered per frame
  24720. */
  24721. Scene.prototype.getActiveIndices = function () {
  24722. return this._activeIndices.current;
  24723. };
  24724. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24725. /**
  24726. * Gets the performance counter for active indices
  24727. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24728. */
  24729. get: function () {
  24730. return this._activeIndices;
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. /**
  24736. * Gets the total number of active particles rendered per frame
  24737. * @returns the total number of active particles rendered per frame
  24738. */
  24739. Scene.prototype.getActiveParticles = function () {
  24740. return this._activeParticles.current;
  24741. };
  24742. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24743. /**
  24744. * Gets the performance counter for active particles
  24745. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24746. */
  24747. get: function () {
  24748. return this._activeParticles;
  24749. },
  24750. enumerable: true,
  24751. configurable: true
  24752. });
  24753. /**
  24754. * Gets the total number of active bones rendered per frame
  24755. * @returns the total number of active bones rendered per frame
  24756. */
  24757. Scene.prototype.getActiveBones = function () {
  24758. return this._activeBones.current;
  24759. };
  24760. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24761. /**
  24762. * Gets the performance counter for active bones
  24763. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24764. */
  24765. get: function () {
  24766. return this._activeBones;
  24767. },
  24768. enumerable: true,
  24769. configurable: true
  24770. });
  24771. /** @hidden */
  24772. Scene.prototype.getInterFramePerfCounter = function () {
  24773. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24774. return 0;
  24775. };
  24776. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24777. /** @hidden */
  24778. get: function () {
  24779. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24780. return null;
  24781. },
  24782. enumerable: true,
  24783. configurable: true
  24784. });
  24785. /** @hidden */
  24786. Scene.prototype.getLastFrameDuration = function () {
  24787. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24788. return 0;
  24789. };
  24790. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24791. /** @hidden */
  24792. get: function () {
  24793. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24794. return null;
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. /** @hidden */
  24800. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24801. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24802. return 0;
  24803. };
  24804. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24805. /** @hidden */
  24806. get: function () {
  24807. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24808. return null;
  24809. },
  24810. enumerable: true,
  24811. configurable: true
  24812. });
  24813. /**
  24814. * Gets the array of active meshes
  24815. * @returns an array of AbstractMesh
  24816. */
  24817. Scene.prototype.getActiveMeshes = function () {
  24818. return this._activeMeshes;
  24819. };
  24820. /** @hidden */
  24821. Scene.prototype.getRenderTargetsDuration = function () {
  24822. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24823. return 0;
  24824. };
  24825. /** @hidden */
  24826. Scene.prototype.getRenderDuration = function () {
  24827. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24828. return 0;
  24829. };
  24830. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24831. /** @hidden */
  24832. get: function () {
  24833. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24834. return null;
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. /** @hidden */
  24840. Scene.prototype.getParticlesDuration = function () {
  24841. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24842. return 0;
  24843. };
  24844. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24845. /** @hidden */
  24846. get: function () {
  24847. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24848. return null;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. /** @hidden */
  24854. Scene.prototype.getSpritesDuration = function () {
  24855. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24856. return 0;
  24857. };
  24858. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24859. /** @hidden */
  24860. get: function () {
  24861. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24862. return null;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /**
  24868. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24869. * @returns a number
  24870. */
  24871. Scene.prototype.getAnimationRatio = function () {
  24872. return this._animationRatio;
  24873. };
  24874. /**
  24875. * Gets an unique Id for the current frame
  24876. * @returns a number
  24877. */
  24878. Scene.prototype.getRenderId = function () {
  24879. return this._renderId;
  24880. };
  24881. /** Call this function if you want to manually increment the render Id*/
  24882. Scene.prototype.incrementRenderId = function () {
  24883. this._renderId++;
  24884. };
  24885. Scene.prototype._updatePointerPosition = function (evt) {
  24886. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24887. if (!canvasRect) {
  24888. return;
  24889. }
  24890. this._pointerX = evt.clientX - canvasRect.left;
  24891. this._pointerY = evt.clientY - canvasRect.top;
  24892. this._unTranslatedPointerX = this._pointerX;
  24893. this._unTranslatedPointerY = this._pointerY;
  24894. };
  24895. Scene.prototype._createUbo = function () {
  24896. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24897. this._sceneUbo.addUniform("viewProjection", 16);
  24898. this._sceneUbo.addUniform("view", 16);
  24899. };
  24900. Scene.prototype._createAlternateUbo = function () {
  24901. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24902. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24903. this._alternateSceneUbo.addUniform("view", 16);
  24904. };
  24905. // Pointers handling
  24906. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24907. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24908. if (result) {
  24909. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24910. }
  24911. return result;
  24912. };
  24913. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24914. if (pointerInfo.pickInfo) {
  24915. if (!pointerInfo.pickInfo.ray) {
  24916. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24917. }
  24918. }
  24919. };
  24920. /**
  24921. * Use this method to simulate a pointer move on a mesh
  24922. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24923. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24924. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24925. * @returns the current scene
  24926. */
  24927. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24928. var evt = new PointerEvent("pointermove", pointerEventInit);
  24929. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24930. return this;
  24931. }
  24932. return this._processPointerMove(pickResult, evt);
  24933. };
  24934. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24935. var canvas = this._engine.getRenderingCanvas();
  24936. if (!canvas) {
  24937. return this;
  24938. }
  24939. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24940. this.setPointerOverSprite(null);
  24941. this.setPointerOverMesh(pickResult.pickedMesh);
  24942. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24943. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24944. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24945. }
  24946. else {
  24947. canvas.style.cursor = this.hoverCursor;
  24948. }
  24949. }
  24950. else {
  24951. canvas.style.cursor = this.defaultCursor;
  24952. }
  24953. }
  24954. else {
  24955. this.setPointerOverMesh(null);
  24956. // Sprites
  24957. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24958. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24959. this.setPointerOverSprite(pickResult.pickedSprite);
  24960. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24961. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24962. }
  24963. else {
  24964. canvas.style.cursor = this.hoverCursor;
  24965. }
  24966. }
  24967. else {
  24968. this.setPointerOverSprite(null);
  24969. // Restore pointer
  24970. canvas.style.cursor = this.defaultCursor;
  24971. }
  24972. }
  24973. if (pickResult) {
  24974. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24975. if (this.onPointerMove) {
  24976. this.onPointerMove(evt, pickResult, type);
  24977. }
  24978. if (this.onPointerObservable.hasObservers()) {
  24979. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24980. this._setRayOnPointerInfo(pi);
  24981. this.onPointerObservable.notifyObservers(pi, type);
  24982. }
  24983. }
  24984. return this;
  24985. };
  24986. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  24987. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  24988. if (pickResult) {
  24989. pi.ray = pickResult.ray;
  24990. }
  24991. this.onPrePointerObservable.notifyObservers(pi, type);
  24992. if (pi.skipOnPointerObservable) {
  24993. return true;
  24994. }
  24995. else {
  24996. return false;
  24997. }
  24998. };
  24999. /**
  25000. * Use this method to simulate a pointer down on a mesh
  25001. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25002. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25003. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25004. * @returns the current scene
  25005. */
  25006. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25007. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25008. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25009. return this;
  25010. }
  25011. return this._processPointerDown(pickResult, evt);
  25012. };
  25013. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25014. var _this = this;
  25015. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25016. this._pickedDownMesh = pickResult.pickedMesh;
  25017. var actionManager = pickResult.pickedMesh.actionManager;
  25018. if (actionManager) {
  25019. if (actionManager.hasPickTriggers) {
  25020. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25021. switch (evt.button) {
  25022. case 0:
  25023. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25024. break;
  25025. case 1:
  25026. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25027. break;
  25028. case 2:
  25029. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25030. break;
  25031. }
  25032. }
  25033. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25034. window.setTimeout(function () {
  25035. 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);
  25036. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25037. if (_this._totalPointersPressed !== 0 &&
  25038. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25039. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25040. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25041. _this._startingPointerTime = 0;
  25042. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25043. }
  25044. }
  25045. }, Scene.LongPressDelay);
  25046. }
  25047. }
  25048. }
  25049. if (pickResult) {
  25050. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25051. if (this.onPointerDown) {
  25052. this.onPointerDown(evt, pickResult, type);
  25053. }
  25054. if (this.onPointerObservable.hasObservers()) {
  25055. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25056. this._setRayOnPointerInfo(pi);
  25057. this.onPointerObservable.notifyObservers(pi, type);
  25058. }
  25059. }
  25060. return this;
  25061. };
  25062. /**
  25063. * Use this method to simulate a pointer up on a mesh
  25064. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25065. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25066. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25067. * @returns the current scene
  25068. */
  25069. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25070. var evt = new PointerEvent("pointerup", pointerEventInit);
  25071. var clickInfo = new ClickInfo();
  25072. clickInfo.singleClick = true;
  25073. clickInfo.ignore = true;
  25074. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25075. return this;
  25076. }
  25077. return this._processPointerUp(pickResult, evt, clickInfo);
  25078. };
  25079. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25080. if (pickResult && pickResult && pickResult.pickedMesh) {
  25081. this._pickedUpMesh = pickResult.pickedMesh;
  25082. if (this._pickedDownMesh === this._pickedUpMesh) {
  25083. if (this.onPointerPick) {
  25084. this.onPointerPick(evt, pickResult);
  25085. }
  25086. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25087. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25088. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25089. this._setRayOnPointerInfo(pi);
  25090. this.onPointerObservable.notifyObservers(pi, type_1);
  25091. }
  25092. }
  25093. if (pickResult.pickedMesh.actionManager) {
  25094. if (clickInfo.ignore) {
  25095. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25096. }
  25097. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25098. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25099. }
  25100. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25101. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25102. }
  25103. }
  25104. }
  25105. if (this._pickedDownMesh &&
  25106. this._pickedDownMesh.actionManager &&
  25107. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25108. this._pickedDownMesh !== this._pickedUpMesh) {
  25109. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25110. }
  25111. var type = BABYLON.PointerEventTypes.POINTERUP;
  25112. if (this.onPointerObservable.hasObservers()) {
  25113. if (!clickInfo.ignore) {
  25114. if (!clickInfo.hasSwiped) {
  25115. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25116. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25117. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25118. this._setRayOnPointerInfo(pi);
  25119. this.onPointerObservable.notifyObservers(pi, type_2);
  25120. }
  25121. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25122. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25123. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25124. this._setRayOnPointerInfo(pi);
  25125. this.onPointerObservable.notifyObservers(pi, type_3);
  25126. }
  25127. }
  25128. }
  25129. else {
  25130. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25131. this._setRayOnPointerInfo(pi);
  25132. this.onPointerObservable.notifyObservers(pi, type);
  25133. }
  25134. }
  25135. if (this.onPointerUp) {
  25136. this.onPointerUp(evt, pickResult, type);
  25137. }
  25138. return this;
  25139. };
  25140. /**
  25141. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25142. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25143. * @returns true if the pointer was captured
  25144. */
  25145. Scene.prototype.isPointerCaptured = function (pointerId) {
  25146. if (pointerId === void 0) { pointerId = 0; }
  25147. return this._pointerCaptures[pointerId];
  25148. };
  25149. /**
  25150. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25151. * @param attachUp defines if you want to attach events to pointerup
  25152. * @param attachDown defines if you want to attach events to pointerdown
  25153. * @param attachMove defines if you want to attach events to pointermove
  25154. */
  25155. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25156. var _this = this;
  25157. if (attachUp === void 0) { attachUp = true; }
  25158. if (attachDown === void 0) { attachDown = true; }
  25159. if (attachMove === void 0) { attachMove = true; }
  25160. this._initActionManager = function (act, clickInfo) {
  25161. if (!_this._meshPickProceed) {
  25162. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25163. _this._currentPickResult = pickResult;
  25164. if (pickResult) {
  25165. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25166. }
  25167. _this._meshPickProceed = true;
  25168. }
  25169. return act;
  25170. };
  25171. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25172. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25173. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25174. btn !== _this._previousButtonPressed) {
  25175. _this._doubleClickOccured = false;
  25176. clickInfo.singleClick = true;
  25177. clickInfo.ignore = false;
  25178. cb(clickInfo, _this._currentPickResult);
  25179. }
  25180. };
  25181. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25182. var clickInfo = new ClickInfo();
  25183. _this._currentPickResult = null;
  25184. var act = null;
  25185. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25186. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25187. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25188. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25189. act = _this._initActionManager(act, clickInfo);
  25190. if (act)
  25191. checkPicking = act.hasPickTriggers;
  25192. }
  25193. if (checkPicking) {
  25194. var btn = evt.button;
  25195. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25196. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25197. if (!clickInfo.hasSwiped) {
  25198. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25199. if (!checkSingleClickImmediately) {
  25200. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25201. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25202. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25203. act = _this._initActionManager(act, clickInfo);
  25204. if (act)
  25205. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25206. }
  25207. }
  25208. if (checkSingleClickImmediately) {
  25209. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25210. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25211. btn !== _this._previousButtonPressed) {
  25212. clickInfo.singleClick = true;
  25213. cb(clickInfo, _this._currentPickResult);
  25214. }
  25215. }
  25216. // at least one double click is required to be check and exclusive double click is enabled
  25217. else {
  25218. // wait that no double click has been raised during the double click delay
  25219. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25220. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25221. }
  25222. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25223. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25224. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25225. act = _this._initActionManager(act, clickInfo);
  25226. if (act)
  25227. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25228. }
  25229. if (checkDoubleClick) {
  25230. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25231. if (btn === _this._previousButtonPressed &&
  25232. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25233. !_this._doubleClickOccured) {
  25234. // pointer has not moved for 2 clicks, it's a double click
  25235. if (!clickInfo.hasSwiped &&
  25236. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25237. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25238. _this._previousStartingPointerTime = 0;
  25239. _this._doubleClickOccured = true;
  25240. clickInfo.doubleClick = true;
  25241. clickInfo.ignore = false;
  25242. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25243. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25244. }
  25245. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25246. cb(clickInfo, _this._currentPickResult);
  25247. }
  25248. // if the two successive clicks are too far, it's just two simple clicks
  25249. else {
  25250. _this._doubleClickOccured = false;
  25251. _this._previousStartingPointerTime = _this._startingPointerTime;
  25252. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25253. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25254. _this._previousButtonPressed = btn;
  25255. if (Scene.ExclusiveDoubleClickMode) {
  25256. if (_this._previousDelayedSimpleClickTimeout) {
  25257. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25258. }
  25259. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25260. cb(clickInfo, _this._previousPickResult);
  25261. }
  25262. else {
  25263. cb(clickInfo, _this._currentPickResult);
  25264. }
  25265. }
  25266. }
  25267. // just the first click of the double has been raised
  25268. else {
  25269. _this._doubleClickOccured = false;
  25270. _this._previousStartingPointerTime = _this._startingPointerTime;
  25271. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25272. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25273. _this._previousButtonPressed = btn;
  25274. }
  25275. }
  25276. }
  25277. }
  25278. clickInfo.ignore = true;
  25279. cb(clickInfo, _this._currentPickResult);
  25280. };
  25281. this._spritePredicate = function (sprite) {
  25282. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25283. };
  25284. this._onPointerMove = function (evt) {
  25285. _this._updatePointerPosition(evt);
  25286. // PreObservable support
  25287. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25288. return;
  25289. }
  25290. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25291. return;
  25292. }
  25293. if (!_this.pointerMovePredicate) {
  25294. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25295. }
  25296. // Meshes
  25297. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25298. _this._processPointerMove(pickResult, evt);
  25299. };
  25300. this._onPointerDown = function (evt) {
  25301. _this._totalPointersPressed++;
  25302. _this._pickedDownMesh = null;
  25303. _this._meshPickProceed = false;
  25304. _this._updatePointerPosition(evt);
  25305. if (_this.preventDefaultOnPointerDown && canvas) {
  25306. evt.preventDefault();
  25307. canvas.focus();
  25308. }
  25309. // PreObservable support
  25310. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25311. return;
  25312. }
  25313. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25314. return;
  25315. }
  25316. _this._pointerCaptures[evt.pointerId] = true;
  25317. _this._startingPointerPosition.x = _this._pointerX;
  25318. _this._startingPointerPosition.y = _this._pointerY;
  25319. _this._startingPointerTime = Date.now();
  25320. if (!_this.pointerDownPredicate) {
  25321. _this.pointerDownPredicate = function (mesh) {
  25322. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25323. };
  25324. }
  25325. // Meshes
  25326. _this._pickedDownMesh = null;
  25327. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25328. _this._processPointerDown(pickResult, evt);
  25329. // Sprites
  25330. _this._pickedDownSprite = null;
  25331. if (_this.spriteManagers.length > 0) {
  25332. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25333. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25334. if (pickResult.pickedSprite.actionManager) {
  25335. _this._pickedDownSprite = pickResult.pickedSprite;
  25336. switch (evt.button) {
  25337. case 0:
  25338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25339. break;
  25340. case 1:
  25341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25342. break;
  25343. case 2:
  25344. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25345. break;
  25346. }
  25347. if (pickResult.pickedSprite.actionManager) {
  25348. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25349. }
  25350. }
  25351. }
  25352. }
  25353. };
  25354. this._onPointerUp = function (evt) {
  25355. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25356. return; // So we need to test it the pointer down was pressed before.
  25357. }
  25358. _this._totalPointersPressed--;
  25359. _this._pickedUpMesh = null;
  25360. _this._meshPickProceed = false;
  25361. _this._updatePointerPosition(evt);
  25362. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25363. // PreObservable support
  25364. if (_this.onPrePointerObservable.hasObservers()) {
  25365. if (!clickInfo.ignore) {
  25366. if (!clickInfo.hasSwiped) {
  25367. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25368. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25369. return;
  25370. }
  25371. }
  25372. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25373. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25374. return;
  25375. }
  25376. }
  25377. }
  25378. }
  25379. else {
  25380. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25381. return;
  25382. }
  25383. }
  25384. }
  25385. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25386. return;
  25387. }
  25388. _this._pointerCaptures[evt.pointerId] = false;
  25389. if (!_this.pointerUpPredicate) {
  25390. _this.pointerUpPredicate = function (mesh) {
  25391. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25392. };
  25393. }
  25394. // Meshes
  25395. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25396. _this._initActionManager(null, clickInfo);
  25397. }
  25398. if (!pickResult) {
  25399. pickResult = _this._currentPickResult;
  25400. }
  25401. _this._processPointerUp(pickResult, evt, clickInfo);
  25402. // Sprites
  25403. if (!clickInfo.ignore) {
  25404. if (_this.spriteManagers.length > 0) {
  25405. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25406. if (spritePickResult) {
  25407. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25408. if (spritePickResult.pickedSprite.actionManager) {
  25409. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25410. if (spritePickResult.pickedSprite.actionManager) {
  25411. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25412. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25413. }
  25414. }
  25415. }
  25416. }
  25417. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25418. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25419. }
  25420. }
  25421. }
  25422. }
  25423. _this._previousPickResult = _this._currentPickResult;
  25424. });
  25425. };
  25426. this._onKeyDown = function (evt) {
  25427. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25428. if (_this.onPreKeyboardObservable.hasObservers()) {
  25429. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25430. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25431. if (pi.skipOnPointerObservable) {
  25432. return;
  25433. }
  25434. }
  25435. if (_this.onKeyboardObservable.hasObservers()) {
  25436. var pi = new BABYLON.KeyboardInfo(type, evt);
  25437. _this.onKeyboardObservable.notifyObservers(pi, type);
  25438. }
  25439. if (_this.actionManager) {
  25440. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25441. }
  25442. };
  25443. this._onKeyUp = function (evt) {
  25444. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25445. if (_this.onPreKeyboardObservable.hasObservers()) {
  25446. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25447. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25448. if (pi.skipOnPointerObservable) {
  25449. return;
  25450. }
  25451. }
  25452. if (_this.onKeyboardObservable.hasObservers()) {
  25453. var pi = new BABYLON.KeyboardInfo(type, evt);
  25454. _this.onKeyboardObservable.notifyObservers(pi, type);
  25455. }
  25456. if (_this.actionManager) {
  25457. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25458. }
  25459. };
  25460. var engine = this.getEngine();
  25461. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25462. if (!canvas) {
  25463. return;
  25464. }
  25465. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25466. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25467. });
  25468. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25469. if (!canvas) {
  25470. return;
  25471. }
  25472. canvas.removeEventListener("keydown", _this._onKeyDown);
  25473. canvas.removeEventListener("keyup", _this._onKeyUp);
  25474. });
  25475. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25476. var canvas = this._engine.getRenderingCanvas();
  25477. if (!canvas) {
  25478. return;
  25479. }
  25480. if (attachMove) {
  25481. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25482. // Wheel
  25483. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25484. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25485. }
  25486. if (attachDown) {
  25487. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25488. }
  25489. if (attachUp) {
  25490. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25491. }
  25492. canvas.tabIndex = 1;
  25493. };
  25494. /** Detaches all event handlers*/
  25495. Scene.prototype.detachControl = function () {
  25496. var engine = this.getEngine();
  25497. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25498. var canvas = engine.getRenderingCanvas();
  25499. if (!canvas) {
  25500. return;
  25501. }
  25502. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25503. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25504. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25505. if (this._onCanvasBlurObserver) {
  25506. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25507. }
  25508. if (this._onCanvasFocusObserver) {
  25509. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25510. }
  25511. // Wheel
  25512. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25513. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25514. // Keyboard
  25515. canvas.removeEventListener("keydown", this._onKeyDown);
  25516. canvas.removeEventListener("keyup", this._onKeyUp);
  25517. // Observables
  25518. this.onKeyboardObservable.clear();
  25519. this.onPreKeyboardObservable.clear();
  25520. this.onPointerObservable.clear();
  25521. this.onPrePointerObservable.clear();
  25522. };
  25523. /**
  25524. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25525. * Delay loaded resources are not taking in account
  25526. * @return true if all required resources are ready
  25527. */
  25528. Scene.prototype.isReady = function () {
  25529. if (this._isDisposed) {
  25530. return false;
  25531. }
  25532. if (this._pendingData.length > 0) {
  25533. return false;
  25534. }
  25535. var index;
  25536. var engine = this.getEngine();
  25537. // Geometries
  25538. for (index = 0; index < this.geometries.length; index++) {
  25539. var geometry = this.geometries[index];
  25540. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25541. return false;
  25542. }
  25543. }
  25544. // Meshes
  25545. for (index = 0; index < this.meshes.length; index++) {
  25546. var mesh = this.meshes[index];
  25547. if (!mesh.isEnabled()) {
  25548. continue;
  25549. }
  25550. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25551. continue;
  25552. }
  25553. if (!mesh.isReady(true)) {
  25554. return false;
  25555. }
  25556. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25557. // Is Ready For Mesh
  25558. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25559. var step = _a[_i];
  25560. if (!step.action(mesh, hardwareInstancedRendering)) {
  25561. return false;
  25562. }
  25563. }
  25564. }
  25565. // Post-processes
  25566. if (this.activeCameras && this.activeCameras.length > 0) {
  25567. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25568. var camera = _c[_b];
  25569. if (!camera.isReady(true)) {
  25570. return false;
  25571. }
  25572. }
  25573. }
  25574. else if (this.activeCamera) {
  25575. if (!this.activeCamera.isReady(true)) {
  25576. return false;
  25577. }
  25578. }
  25579. // Particles
  25580. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25581. var particleSystem = _e[_d];
  25582. if (!particleSystem.isReady()) {
  25583. return false;
  25584. }
  25585. }
  25586. return true;
  25587. };
  25588. /** Resets all cached information relative to material (including effect and visibility) */
  25589. Scene.prototype.resetCachedMaterial = function () {
  25590. this._cachedMaterial = null;
  25591. this._cachedEffect = null;
  25592. this._cachedVisibility = null;
  25593. };
  25594. /**
  25595. * Registers a function to be called before every frame render
  25596. * @param func defines the function to register
  25597. */
  25598. Scene.prototype.registerBeforeRender = function (func) {
  25599. this.onBeforeRenderObservable.add(func);
  25600. };
  25601. /**
  25602. * Unregisters a function called before every frame render
  25603. * @param func defines the function to unregister
  25604. */
  25605. Scene.prototype.unregisterBeforeRender = function (func) {
  25606. this.onBeforeRenderObservable.removeCallback(func);
  25607. };
  25608. /**
  25609. * Registers a function to be called after every frame render
  25610. * @param func defines the function to register
  25611. */
  25612. Scene.prototype.registerAfterRender = function (func) {
  25613. this.onAfterRenderObservable.add(func);
  25614. };
  25615. /**
  25616. * Unregisters a function called after every frame render
  25617. * @param func defines the function to unregister
  25618. */
  25619. Scene.prototype.unregisterAfterRender = function (func) {
  25620. this.onAfterRenderObservable.removeCallback(func);
  25621. };
  25622. Scene.prototype._executeOnceBeforeRender = function (func) {
  25623. var _this = this;
  25624. var execFunc = function () {
  25625. func();
  25626. setTimeout(function () {
  25627. _this.unregisterBeforeRender(execFunc);
  25628. });
  25629. };
  25630. this.registerBeforeRender(execFunc);
  25631. };
  25632. /**
  25633. * The provided function will run before render once and will be disposed afterwards.
  25634. * A timeout delay can be provided so that the function will be executed in N ms.
  25635. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25636. * @param func The function to be executed.
  25637. * @param timeout optional delay in ms
  25638. */
  25639. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25640. var _this = this;
  25641. if (timeout !== undefined) {
  25642. setTimeout(function () {
  25643. _this._executeOnceBeforeRender(func);
  25644. }, timeout);
  25645. }
  25646. else {
  25647. this._executeOnceBeforeRender(func);
  25648. }
  25649. };
  25650. /** @hidden */
  25651. Scene.prototype._addPendingData = function (data) {
  25652. this._pendingData.push(data);
  25653. };
  25654. /** @hidden */
  25655. Scene.prototype._removePendingData = function (data) {
  25656. var wasLoading = this.isLoading;
  25657. var index = this._pendingData.indexOf(data);
  25658. if (index !== -1) {
  25659. this._pendingData.splice(index, 1);
  25660. }
  25661. if (wasLoading && !this.isLoading) {
  25662. this.onDataLoadedObservable.notifyObservers(this);
  25663. }
  25664. };
  25665. /**
  25666. * Returns the number of items waiting to be loaded
  25667. * @returns the number of items waiting to be loaded
  25668. */
  25669. Scene.prototype.getWaitingItemsCount = function () {
  25670. return this._pendingData.length;
  25671. };
  25672. Object.defineProperty(Scene.prototype, "isLoading", {
  25673. /**
  25674. * Returns a boolean indicating if the scene is still loading data
  25675. */
  25676. get: function () {
  25677. return this._pendingData.length > 0;
  25678. },
  25679. enumerable: true,
  25680. configurable: true
  25681. });
  25682. /**
  25683. * Registers a function to be executed when the scene is ready
  25684. * @param {Function} func - the function to be executed
  25685. */
  25686. Scene.prototype.executeWhenReady = function (func) {
  25687. var _this = this;
  25688. this.onReadyObservable.add(func);
  25689. if (this._executeWhenReadyTimeoutId !== -1) {
  25690. return;
  25691. }
  25692. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25693. _this._checkIsReady();
  25694. }, 150);
  25695. };
  25696. /**
  25697. * Returns a promise that resolves when the scene is ready
  25698. * @returns A promise that resolves when the scene is ready
  25699. */
  25700. Scene.prototype.whenReadyAsync = function () {
  25701. var _this = this;
  25702. return new Promise(function (resolve) {
  25703. _this.executeWhenReady(function () {
  25704. resolve();
  25705. });
  25706. });
  25707. };
  25708. /** @hidden */
  25709. Scene.prototype._checkIsReady = function () {
  25710. var _this = this;
  25711. this._registerTransientComponents();
  25712. if (this.isReady()) {
  25713. this.onReadyObservable.notifyObservers(this);
  25714. this.onReadyObservable.clear();
  25715. this._executeWhenReadyTimeoutId = -1;
  25716. return;
  25717. }
  25718. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25719. _this._checkIsReady();
  25720. }, 150);
  25721. };
  25722. // Animations
  25723. /**
  25724. * Will start the animation sequence of a given target
  25725. * @param target defines the target
  25726. * @param from defines from which frame should animation start
  25727. * @param to defines until which frame should animation run.
  25728. * @param weight defines the weight to apply to the animation (1.0 by default)
  25729. * @param loop defines if the animation loops
  25730. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25731. * @param onAnimationEnd defines the function to be executed when the animation ends
  25732. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25733. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25734. * @returns the animatable object created for this animation
  25735. */
  25736. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25737. if (weight === void 0) { weight = 1.0; }
  25738. if (speedRatio === void 0) { speedRatio = 1.0; }
  25739. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25740. returnedAnimatable.weight = weight;
  25741. return returnedAnimatable;
  25742. };
  25743. /**
  25744. * Will start the animation sequence of a given target
  25745. * @param target defines the target
  25746. * @param from defines from which frame should animation start
  25747. * @param to defines until which frame should animation run.
  25748. * @param loop defines if the animation loops
  25749. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25750. * @param onAnimationEnd defines the function to be executed when the animation ends
  25751. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25752. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25753. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25754. * @returns the animatable object created for this animation
  25755. */
  25756. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25757. if (speedRatio === void 0) { speedRatio = 1.0; }
  25758. if (stopCurrent === void 0) { stopCurrent = true; }
  25759. if (from > to && speedRatio > 0) {
  25760. speedRatio *= -1;
  25761. }
  25762. if (stopCurrent) {
  25763. this.stopAnimation(target, undefined, targetMask);
  25764. }
  25765. if (!animatable) {
  25766. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25767. }
  25768. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25769. // Local animations
  25770. if (target.animations && shouldRunTargetAnimations) {
  25771. animatable.appendAnimations(target, target.animations);
  25772. }
  25773. // Children animations
  25774. if (target.getAnimatables) {
  25775. var animatables = target.getAnimatables();
  25776. for (var index = 0; index < animatables.length; index++) {
  25777. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25778. }
  25779. }
  25780. animatable.reset();
  25781. return animatable;
  25782. };
  25783. /**
  25784. * Begin a new animation on a given node
  25785. * @param target defines the target where the animation will take place
  25786. * @param animations defines the list of animations to start
  25787. * @param from defines the initial value
  25788. * @param to defines the final value
  25789. * @param loop defines if you want animation to loop (off by default)
  25790. * @param speedRatio defines the speed ratio to apply to all animations
  25791. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25792. * @returns the list of created animatables
  25793. */
  25794. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25795. if (speedRatio === undefined) {
  25796. speedRatio = 1.0;
  25797. }
  25798. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25799. return animatable;
  25800. };
  25801. /**
  25802. * Begin a new animation on a given node and its hierarchy
  25803. * @param target defines the root node where the animation will take place
  25804. * @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.
  25805. * @param animations defines the list of animations to start
  25806. * @param from defines the initial value
  25807. * @param to defines the final value
  25808. * @param loop defines if you want animation to loop (off by default)
  25809. * @param speedRatio defines the speed ratio to apply to all animations
  25810. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25811. * @returns the list of animatables created for all nodes
  25812. */
  25813. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25814. var children = target.getDescendants(directDescendantsOnly);
  25815. var result = [];
  25816. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25817. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25818. var child = children_1[_i];
  25819. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25820. }
  25821. return result;
  25822. };
  25823. /**
  25824. * Gets the animatable associated with a specific target
  25825. * @param target defines the target of the animatable
  25826. * @returns the required animatable if found
  25827. */
  25828. Scene.prototype.getAnimatableByTarget = function (target) {
  25829. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25830. if (this._activeAnimatables[index].target === target) {
  25831. return this._activeAnimatables[index];
  25832. }
  25833. }
  25834. return null;
  25835. };
  25836. /**
  25837. * Gets all animatables associated with a given target
  25838. * @param target defines the target to look animatables for
  25839. * @returns an array of Animatables
  25840. */
  25841. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25842. var result = [];
  25843. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25844. if (this._activeAnimatables[index].target === target) {
  25845. result.push(this._activeAnimatables[index]);
  25846. }
  25847. }
  25848. return result;
  25849. };
  25850. Object.defineProperty(Scene.prototype, "animatables", {
  25851. /**
  25852. * Gets all animatable attached to the scene
  25853. */
  25854. get: function () {
  25855. return this._activeAnimatables;
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. /**
  25861. * Will stop the animation of the given target
  25862. * @param target - the target
  25863. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25864. * @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)
  25865. */
  25866. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25867. var animatables = this.getAllAnimatablesByTarget(target);
  25868. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25869. var animatable = animatables_1[_i];
  25870. animatable.stop(animationName, targetMask);
  25871. }
  25872. };
  25873. /**
  25874. * Stops and removes all animations that have been applied to the scene
  25875. */
  25876. Scene.prototype.stopAllAnimations = function () {
  25877. if (this._activeAnimatables) {
  25878. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25879. this._activeAnimatables[i].stop();
  25880. }
  25881. this._activeAnimatables = [];
  25882. }
  25883. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25884. var group = _a[_i];
  25885. group.stop();
  25886. }
  25887. };
  25888. Scene.prototype._animate = function () {
  25889. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25890. return;
  25891. }
  25892. // Getting time
  25893. var now = BABYLON.Tools.Now;
  25894. if (!this._animationTimeLast) {
  25895. if (this._pendingData.length > 0) {
  25896. return;
  25897. }
  25898. this._animationTimeLast = now;
  25899. }
  25900. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25901. this._animationTime += deltaTime;
  25902. this._animationTimeLast = now;
  25903. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25904. this._activeAnimatables[index]._animate(this._animationTime);
  25905. }
  25906. // Late animation bindings
  25907. this._processLateAnimationBindings();
  25908. };
  25909. /** @hidden */
  25910. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25911. var target = runtimeAnimation.target;
  25912. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25913. if (!target._lateAnimationHolders) {
  25914. target._lateAnimationHolders = {};
  25915. }
  25916. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25917. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25918. totalWeight: 0,
  25919. animations: [],
  25920. originalValue: originalValue
  25921. };
  25922. }
  25923. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25924. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25925. };
  25926. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25927. var normalizer = 1.0;
  25928. var finalPosition = BABYLON.Tmp.Vector3[0];
  25929. var finalScaling = BABYLON.Tmp.Vector3[1];
  25930. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25931. var startIndex = 0;
  25932. var originalAnimation = holder.animations[0];
  25933. var originalValue = holder.originalValue;
  25934. var scale = 1;
  25935. if (holder.totalWeight < 1.0) {
  25936. // We need to mix the original value in
  25937. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25938. scale = 1.0 - holder.totalWeight;
  25939. }
  25940. else {
  25941. startIndex = 1;
  25942. // We need to normalize the weights
  25943. normalizer = holder.totalWeight;
  25944. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25945. scale = originalAnimation.weight / normalizer;
  25946. if (scale == 1) {
  25947. return originalAnimation.currentValue;
  25948. }
  25949. }
  25950. finalScaling.scaleInPlace(scale);
  25951. finalPosition.scaleInPlace(scale);
  25952. finalQuaternion.scaleInPlace(scale);
  25953. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25954. var runtimeAnimation = holder.animations[animIndex];
  25955. var scale = runtimeAnimation.weight / normalizer;
  25956. var currentPosition = BABYLON.Tmp.Vector3[2];
  25957. var currentScaling = BABYLON.Tmp.Vector3[3];
  25958. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25959. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25960. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25961. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25962. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25963. }
  25964. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25965. return originalAnimation._workValue;
  25966. };
  25967. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25968. var originalAnimation = holder.animations[0];
  25969. var originalValue = holder.originalValue;
  25970. if (holder.animations.length === 1) {
  25971. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25972. }
  25973. var normalizer = 1.0;
  25974. var quaternions;
  25975. var weights;
  25976. if (holder.totalWeight < 1.0) {
  25977. var scale = 1.0 - holder.totalWeight;
  25978. quaternions = [];
  25979. weights = [];
  25980. quaternions.push(originalValue);
  25981. weights.push(scale);
  25982. }
  25983. else {
  25984. if (holder.animations.length === 2) { // Slerp as soon as we can
  25985. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25986. }
  25987. quaternions = [];
  25988. weights = [];
  25989. normalizer = holder.totalWeight;
  25990. }
  25991. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25992. var runtimeAnimation = holder.animations[animIndex];
  25993. quaternions.push(runtimeAnimation.currentValue);
  25994. weights.push(runtimeAnimation.weight / normalizer);
  25995. }
  25996. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25997. var cumulativeAmount = 0;
  25998. var cumulativeQuaternion = null;
  25999. for (var index = 0; index < quaternions.length;) {
  26000. if (!cumulativeQuaternion) {
  26001. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26002. cumulativeAmount = weights[index] + weights[index + 1];
  26003. index += 2;
  26004. continue;
  26005. }
  26006. cumulativeAmount += weights[index];
  26007. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26008. index++;
  26009. }
  26010. return cumulativeQuaternion;
  26011. };
  26012. Scene.prototype._processLateAnimationBindings = function () {
  26013. if (!this._registeredForLateAnimationBindings.length) {
  26014. return;
  26015. }
  26016. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26017. var target = this._registeredForLateAnimationBindings.data[index];
  26018. for (var path in target._lateAnimationHolders) {
  26019. var holder = target._lateAnimationHolders[path];
  26020. var originalAnimation = holder.animations[0];
  26021. var originalValue = holder.originalValue;
  26022. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26023. var finalValue = void 0;
  26024. if (matrixDecomposeMode) {
  26025. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26026. }
  26027. else {
  26028. var quaternionMode = originalValue.w !== undefined;
  26029. if (quaternionMode) {
  26030. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26031. }
  26032. else {
  26033. var startIndex = 0;
  26034. var normalizer = 1.0;
  26035. if (holder.totalWeight < 1.0) {
  26036. // We need to mix the original value in
  26037. if (originalValue.scale) {
  26038. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26039. }
  26040. else {
  26041. finalValue = originalValue * (1.0 - holder.totalWeight);
  26042. }
  26043. }
  26044. else {
  26045. // We need to normalize the weights
  26046. normalizer = holder.totalWeight;
  26047. var scale_1 = originalAnimation.weight / normalizer;
  26048. if (scale_1 !== 1) {
  26049. if (originalAnimation.currentValue.scale) {
  26050. finalValue = originalAnimation.currentValue.scale(scale_1);
  26051. }
  26052. else {
  26053. finalValue = originalAnimation.currentValue * scale_1;
  26054. }
  26055. }
  26056. else {
  26057. finalValue = originalAnimation.currentValue;
  26058. }
  26059. startIndex = 1;
  26060. }
  26061. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26062. var runtimeAnimation = holder.animations[animIndex];
  26063. var scale = runtimeAnimation.weight / normalizer;
  26064. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26065. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26066. }
  26067. else {
  26068. finalValue += runtimeAnimation.currentValue * scale;
  26069. }
  26070. }
  26071. }
  26072. }
  26073. target[path] = finalValue;
  26074. }
  26075. target._lateAnimationHolders = {};
  26076. }
  26077. this._registeredForLateAnimationBindings.reset();
  26078. };
  26079. // Matrix
  26080. /** @hidden */
  26081. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26082. this._useAlternateCameraConfiguration = active;
  26083. };
  26084. /**
  26085. * Gets the current view matrix
  26086. * @returns a Matrix
  26087. */
  26088. Scene.prototype.getViewMatrix = function () {
  26089. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26090. };
  26091. /**
  26092. * Gets the current projection matrix
  26093. * @returns a Matrix
  26094. */
  26095. Scene.prototype.getProjectionMatrix = function () {
  26096. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26097. };
  26098. /**
  26099. * Gets the current transform matrix
  26100. * @returns a Matrix made of View * Projection
  26101. */
  26102. Scene.prototype.getTransformMatrix = function () {
  26103. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26104. };
  26105. /**
  26106. * Sets the current transform matrix
  26107. * @param view defines the View matrix to use
  26108. * @param projection defines the Projection matrix to use
  26109. */
  26110. Scene.prototype.setTransformMatrix = function (view, projection) {
  26111. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26112. return;
  26113. }
  26114. this._viewUpdateFlag = view.updateFlag;
  26115. this._projectionUpdateFlag = projection.updateFlag;
  26116. this._viewMatrix = view;
  26117. this._projectionMatrix = projection;
  26118. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26119. // Update frustum
  26120. if (!this._frustumPlanes) {
  26121. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26122. }
  26123. else {
  26124. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26125. }
  26126. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26127. var otherCamera = this.activeCamera._alternateCamera;
  26128. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26129. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26130. }
  26131. if (this._sceneUbo.useUbo) {
  26132. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26133. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26134. this._sceneUbo.update();
  26135. }
  26136. };
  26137. /** @hidden */
  26138. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26139. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26140. return;
  26141. }
  26142. this._alternateViewUpdateFlag = view.updateFlag;
  26143. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26144. this._alternateViewMatrix = view;
  26145. this._alternateProjectionMatrix = projection;
  26146. if (!this._alternateTransformMatrix) {
  26147. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26148. }
  26149. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26150. if (!this._alternateSceneUbo) {
  26151. this._createAlternateUbo();
  26152. }
  26153. if (this._alternateSceneUbo.useUbo) {
  26154. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26155. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26156. this._alternateSceneUbo.update();
  26157. }
  26158. };
  26159. /**
  26160. * Gets the uniform buffer used to store scene data
  26161. * @returns a UniformBuffer
  26162. */
  26163. Scene.prototype.getSceneUniformBuffer = function () {
  26164. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26165. };
  26166. /**
  26167. * Gets an unique (relatively to the current scene) Id
  26168. * @returns an unique number for the scene
  26169. */
  26170. Scene.prototype.getUniqueId = function () {
  26171. var result = Scene._uniqueIdCounter;
  26172. Scene._uniqueIdCounter++;
  26173. return result;
  26174. };
  26175. /**
  26176. * Add a mesh to the list of scene's meshes
  26177. * @param newMesh defines the mesh to add
  26178. * @param recursive if all child meshes should also be added to the scene
  26179. */
  26180. Scene.prototype.addMesh = function (newMesh, recursive) {
  26181. var _this = this;
  26182. if (recursive === void 0) { recursive = false; }
  26183. this.meshes.push(newMesh);
  26184. //notify the collision coordinator
  26185. if (this.collisionCoordinator) {
  26186. this.collisionCoordinator.onMeshAdded(newMesh);
  26187. }
  26188. newMesh._resyncLightSources();
  26189. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26190. if (recursive) {
  26191. newMesh.getChildMeshes().forEach(function (m) {
  26192. _this.addMesh(m);
  26193. });
  26194. }
  26195. };
  26196. /**
  26197. * Remove a mesh for the list of scene's meshes
  26198. * @param toRemove defines the mesh to remove
  26199. * @param recursive if all child meshes should also be removed from the scene
  26200. * @returns the index where the mesh was in the mesh list
  26201. */
  26202. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26203. var _this = this;
  26204. if (recursive === void 0) { recursive = false; }
  26205. var index = this.meshes.indexOf(toRemove);
  26206. if (index !== -1) {
  26207. // Remove from the scene if mesh found
  26208. this.meshes.splice(index, 1);
  26209. }
  26210. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26211. if (recursive) {
  26212. toRemove.getChildMeshes().forEach(function (m) {
  26213. _this.removeMesh(m);
  26214. });
  26215. }
  26216. return index;
  26217. };
  26218. /**
  26219. * Add a transform node to the list of scene's transform nodes
  26220. * @param newTransformNode defines the transform node to add
  26221. */
  26222. Scene.prototype.addTransformNode = function (newTransformNode) {
  26223. this.transformNodes.push(newTransformNode);
  26224. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26225. };
  26226. /**
  26227. * Remove a transform node for the list of scene's transform nodes
  26228. * @param toRemove defines the transform node to remove
  26229. * @returns the index where the transform node was in the transform node list
  26230. */
  26231. Scene.prototype.removeTransformNode = function (toRemove) {
  26232. var index = this.transformNodes.indexOf(toRemove);
  26233. if (index !== -1) {
  26234. // Remove from the scene if found
  26235. this.transformNodes.splice(index, 1);
  26236. }
  26237. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26238. return index;
  26239. };
  26240. /**
  26241. * Remove a skeleton for the list of scene's skeletons
  26242. * @param toRemove defines the skeleton to remove
  26243. * @returns the index where the skeleton was in the skeleton list
  26244. */
  26245. Scene.prototype.removeSkeleton = function (toRemove) {
  26246. var index = this.skeletons.indexOf(toRemove);
  26247. if (index !== -1) {
  26248. // Remove from the scene if found
  26249. this.skeletons.splice(index, 1);
  26250. }
  26251. return index;
  26252. };
  26253. /**
  26254. * Remove a morph target for the list of scene's morph targets
  26255. * @param toRemove defines the morph target to remove
  26256. * @returns the index where the morph target was in the morph target list
  26257. */
  26258. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26259. var index = this.morphTargetManagers.indexOf(toRemove);
  26260. if (index !== -1) {
  26261. // Remove from the scene if found
  26262. this.morphTargetManagers.splice(index, 1);
  26263. }
  26264. return index;
  26265. };
  26266. /**
  26267. * Remove a light for the list of scene's lights
  26268. * @param toRemove defines the light to remove
  26269. * @returns the index where the light was in the light list
  26270. */
  26271. Scene.prototype.removeLight = function (toRemove) {
  26272. var index = this.lights.indexOf(toRemove);
  26273. if (index !== -1) {
  26274. // Remove from meshes
  26275. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26276. var mesh = _a[_i];
  26277. mesh._removeLightSource(toRemove);
  26278. }
  26279. // Remove from the scene if mesh found
  26280. this.lights.splice(index, 1);
  26281. this.sortLightsByPriority();
  26282. }
  26283. this.onLightRemovedObservable.notifyObservers(toRemove);
  26284. return index;
  26285. };
  26286. /**
  26287. * Remove a camera for the list of scene's cameras
  26288. * @param toRemove defines the camera to remove
  26289. * @returns the index where the camera was in the camera list
  26290. */
  26291. Scene.prototype.removeCamera = function (toRemove) {
  26292. var index = this.cameras.indexOf(toRemove);
  26293. if (index !== -1) {
  26294. // Remove from the scene if mesh found
  26295. this.cameras.splice(index, 1);
  26296. }
  26297. // Remove from activeCameras
  26298. var index2 = this.activeCameras.indexOf(toRemove);
  26299. if (index2 !== -1) {
  26300. // Remove from the scene if mesh found
  26301. this.activeCameras.splice(index2, 1);
  26302. }
  26303. // Reset the activeCamera
  26304. if (this.activeCamera === toRemove) {
  26305. if (this.cameras.length > 0) {
  26306. this.activeCamera = this.cameras[0];
  26307. }
  26308. else {
  26309. this.activeCamera = null;
  26310. }
  26311. }
  26312. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26313. return index;
  26314. };
  26315. /**
  26316. * Remove a particle system for the list of scene's particle systems
  26317. * @param toRemove defines the particle system to remove
  26318. * @returns the index where the particle system was in the particle system list
  26319. */
  26320. Scene.prototype.removeParticleSystem = function (toRemove) {
  26321. var index = this.particleSystems.indexOf(toRemove);
  26322. if (index !== -1) {
  26323. this.particleSystems.splice(index, 1);
  26324. }
  26325. return index;
  26326. };
  26327. /**
  26328. * Remove a animation for the list of scene's animations
  26329. * @param toRemove defines the animation to remove
  26330. * @returns the index where the animation was in the animation list
  26331. */
  26332. Scene.prototype.removeAnimation = function (toRemove) {
  26333. var index = this.animations.indexOf(toRemove);
  26334. if (index !== -1) {
  26335. this.animations.splice(index, 1);
  26336. }
  26337. return index;
  26338. };
  26339. /**
  26340. * Removes the given animation group from this scene.
  26341. * @param toRemove The animation group to remove
  26342. * @returns The index of the removed animation group
  26343. */
  26344. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26345. var index = this.animationGroups.indexOf(toRemove);
  26346. if (index !== -1) {
  26347. this.animationGroups.splice(index, 1);
  26348. }
  26349. return index;
  26350. };
  26351. /**
  26352. * Removes the given multi-material from this scene.
  26353. * @param toRemove The multi-material to remove
  26354. * @returns The index of the removed multi-material
  26355. */
  26356. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26357. var index = this.multiMaterials.indexOf(toRemove);
  26358. if (index !== -1) {
  26359. this.multiMaterials.splice(index, 1);
  26360. }
  26361. return index;
  26362. };
  26363. /**
  26364. * Removes the given material from this scene.
  26365. * @param toRemove The material to remove
  26366. * @returns The index of the removed material
  26367. */
  26368. Scene.prototype.removeMaterial = function (toRemove) {
  26369. var index = this.materials.indexOf(toRemove);
  26370. if (index !== -1) {
  26371. this.materials.splice(index, 1);
  26372. }
  26373. return index;
  26374. };
  26375. /**
  26376. * Removes the given action manager from this scene.
  26377. * @param toRemove The action manager to remove
  26378. * @returns The index of the removed action manager
  26379. */
  26380. Scene.prototype.removeActionManager = function (toRemove) {
  26381. var index = this.actionManagers.indexOf(toRemove);
  26382. if (index !== -1) {
  26383. this.actionManagers.splice(index, 1);
  26384. }
  26385. return index;
  26386. };
  26387. /**
  26388. * Removes the given texture from this scene.
  26389. * @param toRemove The texture to remove
  26390. * @returns The index of the removed texture
  26391. */
  26392. Scene.prototype.removeTexture = function (toRemove) {
  26393. var index = this.textures.indexOf(toRemove);
  26394. if (index !== -1) {
  26395. this.textures.splice(index, 1);
  26396. }
  26397. return index;
  26398. };
  26399. /**
  26400. * Adds the given light to this scene
  26401. * @param newLight The light to add
  26402. */
  26403. Scene.prototype.addLight = function (newLight) {
  26404. this.lights.push(newLight);
  26405. this.sortLightsByPriority();
  26406. // Add light to all meshes (To support if the light is removed and then readded)
  26407. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26408. var mesh = _a[_i];
  26409. if (mesh._lightSources.indexOf(newLight) === -1) {
  26410. mesh._lightSources.push(newLight);
  26411. mesh._resyncLightSources();
  26412. }
  26413. }
  26414. this.onNewLightAddedObservable.notifyObservers(newLight);
  26415. };
  26416. /**
  26417. * Sorts the list list based on light priorities
  26418. */
  26419. Scene.prototype.sortLightsByPriority = function () {
  26420. if (this.requireLightSorting) {
  26421. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26422. }
  26423. };
  26424. /**
  26425. * Adds the given camera to this scene
  26426. * @param newCamera The camera to add
  26427. */
  26428. Scene.prototype.addCamera = function (newCamera) {
  26429. this.cameras.push(newCamera);
  26430. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26431. };
  26432. /**
  26433. * Adds the given skeleton to this scene
  26434. * @param newSkeleton The skeleton to add
  26435. */
  26436. Scene.prototype.addSkeleton = function (newSkeleton) {
  26437. this.skeletons.push(newSkeleton);
  26438. };
  26439. /**
  26440. * Adds the given particle system to this scene
  26441. * @param newParticleSystem The particle system to add
  26442. */
  26443. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26444. this.particleSystems.push(newParticleSystem);
  26445. };
  26446. /**
  26447. * Adds the given animation to this scene
  26448. * @param newAnimation The animation to add
  26449. */
  26450. Scene.prototype.addAnimation = function (newAnimation) {
  26451. this.animations.push(newAnimation);
  26452. };
  26453. /**
  26454. * Adds the given animation group to this scene.
  26455. * @param newAnimationGroup The animation group to add
  26456. */
  26457. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26458. this.animationGroups.push(newAnimationGroup);
  26459. };
  26460. /**
  26461. * Adds the given multi-material to this scene
  26462. * @param newMultiMaterial The multi-material to add
  26463. */
  26464. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26465. this.multiMaterials.push(newMultiMaterial);
  26466. };
  26467. /**
  26468. * Adds the given material to this scene
  26469. * @param newMaterial The material to add
  26470. */
  26471. Scene.prototype.addMaterial = function (newMaterial) {
  26472. this.materials.push(newMaterial);
  26473. };
  26474. /**
  26475. * Adds the given morph target to this scene
  26476. * @param newMorphTargetManager The morph target to add
  26477. */
  26478. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26479. this.morphTargetManagers.push(newMorphTargetManager);
  26480. };
  26481. /**
  26482. * Adds the given geometry to this scene
  26483. * @param newGeometry The geometry to add
  26484. */
  26485. Scene.prototype.addGeometry = function (newGeometry) {
  26486. this.geometries.push(newGeometry);
  26487. };
  26488. /**
  26489. * Adds the given action manager to this scene
  26490. * @param newActionManager The action manager to add
  26491. */
  26492. Scene.prototype.addActionManager = function (newActionManager) {
  26493. this.actionManagers.push(newActionManager);
  26494. };
  26495. /**
  26496. * Adds the given texture to this scene.
  26497. * @param newTexture The texture to add
  26498. */
  26499. Scene.prototype.addTexture = function (newTexture) {
  26500. this.textures.push(newTexture);
  26501. };
  26502. /**
  26503. * Switch active camera
  26504. * @param newCamera defines the new active camera
  26505. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26506. */
  26507. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26508. if (attachControl === void 0) { attachControl = true; }
  26509. var canvas = this._engine.getRenderingCanvas();
  26510. if (!canvas) {
  26511. return;
  26512. }
  26513. if (this.activeCamera) {
  26514. this.activeCamera.detachControl(canvas);
  26515. }
  26516. this.activeCamera = newCamera;
  26517. if (attachControl) {
  26518. newCamera.attachControl(canvas);
  26519. }
  26520. };
  26521. /**
  26522. * sets the active camera of the scene using its ID
  26523. * @param id defines the camera's ID
  26524. * @return the new active camera or null if none found.
  26525. */
  26526. Scene.prototype.setActiveCameraByID = function (id) {
  26527. var camera = this.getCameraByID(id);
  26528. if (camera) {
  26529. this.activeCamera = camera;
  26530. return camera;
  26531. }
  26532. return null;
  26533. };
  26534. /**
  26535. * sets the active camera of the scene using its name
  26536. * @param name defines the camera's name
  26537. * @returns the new active camera or null if none found.
  26538. */
  26539. Scene.prototype.setActiveCameraByName = function (name) {
  26540. var camera = this.getCameraByName(name);
  26541. if (camera) {
  26542. this.activeCamera = camera;
  26543. return camera;
  26544. }
  26545. return null;
  26546. };
  26547. /**
  26548. * get an animation group using its name
  26549. * @param name defines the material's name
  26550. * @return the animation group or null if none found.
  26551. */
  26552. Scene.prototype.getAnimationGroupByName = function (name) {
  26553. for (var index = 0; index < this.animationGroups.length; index++) {
  26554. if (this.animationGroups[index].name === name) {
  26555. return this.animationGroups[index];
  26556. }
  26557. }
  26558. return null;
  26559. };
  26560. /**
  26561. * get a material using its id
  26562. * @param id defines the material's ID
  26563. * @return the material or null if none found.
  26564. */
  26565. Scene.prototype.getMaterialByID = function (id) {
  26566. for (var index = 0; index < this.materials.length; index++) {
  26567. if (this.materials[index].id === id) {
  26568. return this.materials[index];
  26569. }
  26570. }
  26571. return null;
  26572. };
  26573. /**
  26574. * Gets a material using its name
  26575. * @param name defines the material's name
  26576. * @return the material or null if none found.
  26577. */
  26578. Scene.prototype.getMaterialByName = function (name) {
  26579. for (var index = 0; index < this.materials.length; index++) {
  26580. if (this.materials[index].name === name) {
  26581. return this.materials[index];
  26582. }
  26583. }
  26584. return null;
  26585. };
  26586. /**
  26587. * Gets a camera using its id
  26588. * @param id defines the id to look for
  26589. * @returns the camera or null if not found
  26590. */
  26591. Scene.prototype.getCameraByID = function (id) {
  26592. for (var index = 0; index < this.cameras.length; index++) {
  26593. if (this.cameras[index].id === id) {
  26594. return this.cameras[index];
  26595. }
  26596. }
  26597. return null;
  26598. };
  26599. /**
  26600. * Gets a camera using its unique id
  26601. * @param uniqueId defines the unique id to look for
  26602. * @returns the camera or null if not found
  26603. */
  26604. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26605. for (var index = 0; index < this.cameras.length; index++) {
  26606. if (this.cameras[index].uniqueId === uniqueId) {
  26607. return this.cameras[index];
  26608. }
  26609. }
  26610. return null;
  26611. };
  26612. /**
  26613. * Gets a camera using its name
  26614. * @param name defines the camera's name
  26615. * @return the camera or null if none found.
  26616. */
  26617. Scene.prototype.getCameraByName = function (name) {
  26618. for (var index = 0; index < this.cameras.length; index++) {
  26619. if (this.cameras[index].name === name) {
  26620. return this.cameras[index];
  26621. }
  26622. }
  26623. return null;
  26624. };
  26625. /**
  26626. * Gets a bone using its id
  26627. * @param id defines the bone's id
  26628. * @return the bone or null if not found
  26629. */
  26630. Scene.prototype.getBoneByID = function (id) {
  26631. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26632. var skeleton = this.skeletons[skeletonIndex];
  26633. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26634. if (skeleton.bones[boneIndex].id === id) {
  26635. return skeleton.bones[boneIndex];
  26636. }
  26637. }
  26638. }
  26639. return null;
  26640. };
  26641. /**
  26642. * Gets a bone using its id
  26643. * @param name defines the bone's name
  26644. * @return the bone or null if not found
  26645. */
  26646. Scene.prototype.getBoneByName = function (name) {
  26647. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26648. var skeleton = this.skeletons[skeletonIndex];
  26649. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26650. if (skeleton.bones[boneIndex].name === name) {
  26651. return skeleton.bones[boneIndex];
  26652. }
  26653. }
  26654. }
  26655. return null;
  26656. };
  26657. /**
  26658. * Gets a light node using its name
  26659. * @param name defines the the light's name
  26660. * @return the light or null if none found.
  26661. */
  26662. Scene.prototype.getLightByName = function (name) {
  26663. for (var index = 0; index < this.lights.length; index++) {
  26664. if (this.lights[index].name === name) {
  26665. return this.lights[index];
  26666. }
  26667. }
  26668. return null;
  26669. };
  26670. /**
  26671. * Gets a light node using its id
  26672. * @param id defines the light's id
  26673. * @return the light or null if none found.
  26674. */
  26675. Scene.prototype.getLightByID = function (id) {
  26676. for (var index = 0; index < this.lights.length; index++) {
  26677. if (this.lights[index].id === id) {
  26678. return this.lights[index];
  26679. }
  26680. }
  26681. return null;
  26682. };
  26683. /**
  26684. * Gets a light node using its scene-generated unique ID
  26685. * @param uniqueId defines the light's unique id
  26686. * @return the light or null if none found.
  26687. */
  26688. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26689. for (var index = 0; index < this.lights.length; index++) {
  26690. if (this.lights[index].uniqueId === uniqueId) {
  26691. return this.lights[index];
  26692. }
  26693. }
  26694. return null;
  26695. };
  26696. /**
  26697. * Gets a particle system by id
  26698. * @param id defines the particle system id
  26699. * @return the corresponding system or null if none found
  26700. */
  26701. Scene.prototype.getParticleSystemByID = function (id) {
  26702. for (var index = 0; index < this.particleSystems.length; index++) {
  26703. if (this.particleSystems[index].id === id) {
  26704. return this.particleSystems[index];
  26705. }
  26706. }
  26707. return null;
  26708. };
  26709. /**
  26710. * Gets a geometry using its ID
  26711. * @param id defines the geometry's id
  26712. * @return the geometry or null if none found.
  26713. */
  26714. Scene.prototype.getGeometryByID = function (id) {
  26715. for (var index = 0; index < this.geometries.length; index++) {
  26716. if (this.geometries[index].id === id) {
  26717. return this.geometries[index];
  26718. }
  26719. }
  26720. return null;
  26721. };
  26722. /**
  26723. * Add a new geometry to this scene
  26724. * @param geometry defines the geometry to be added to the scene.
  26725. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26726. * @return a boolean defining if the geometry was added or not
  26727. */
  26728. Scene.prototype.pushGeometry = function (geometry, force) {
  26729. if (!force && this.getGeometryByID(geometry.id)) {
  26730. return false;
  26731. }
  26732. this.geometries.push(geometry);
  26733. //notify the collision coordinator
  26734. if (this.collisionCoordinator) {
  26735. this.collisionCoordinator.onGeometryAdded(geometry);
  26736. }
  26737. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26738. return true;
  26739. };
  26740. /**
  26741. * Removes an existing geometry
  26742. * @param geometry defines the geometry to be removed from the scene
  26743. * @return a boolean defining if the geometry was removed or not
  26744. */
  26745. Scene.prototype.removeGeometry = function (geometry) {
  26746. var index = this.geometries.indexOf(geometry);
  26747. if (index > -1) {
  26748. this.geometries.splice(index, 1);
  26749. //notify the collision coordinator
  26750. if (this.collisionCoordinator) {
  26751. this.collisionCoordinator.onGeometryDeleted(geometry);
  26752. }
  26753. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26754. return true;
  26755. }
  26756. return false;
  26757. };
  26758. /**
  26759. * Gets the list of geometries attached to the scene
  26760. * @returns an array of Geometry
  26761. */
  26762. Scene.prototype.getGeometries = function () {
  26763. return this.geometries;
  26764. };
  26765. /**
  26766. * Gets the first added mesh found of a given ID
  26767. * @param id defines the id to search for
  26768. * @return the mesh found or null if not found at all
  26769. */
  26770. Scene.prototype.getMeshByID = function (id) {
  26771. for (var index = 0; index < this.meshes.length; index++) {
  26772. if (this.meshes[index].id === id) {
  26773. return this.meshes[index];
  26774. }
  26775. }
  26776. return null;
  26777. };
  26778. /**
  26779. * Gets a list of meshes using their id
  26780. * @param id defines the id to search for
  26781. * @returns a list of meshes
  26782. */
  26783. Scene.prototype.getMeshesByID = function (id) {
  26784. return this.meshes.filter(function (m) {
  26785. return m.id === id;
  26786. });
  26787. };
  26788. /**
  26789. * Gets the first added transform node found of a given ID
  26790. * @param id defines the id to search for
  26791. * @return the found transform node or null if not found at all.
  26792. */
  26793. Scene.prototype.getTransformNodeByID = function (id) {
  26794. for (var index = 0; index < this.transformNodes.length; index++) {
  26795. if (this.transformNodes[index].id === id) {
  26796. return this.transformNodes[index];
  26797. }
  26798. }
  26799. return null;
  26800. };
  26801. /**
  26802. * Gets a list of transform nodes using their id
  26803. * @param id defines the id to search for
  26804. * @returns a list of transform nodes
  26805. */
  26806. Scene.prototype.getTransformNodesByID = function (id) {
  26807. return this.transformNodes.filter(function (m) {
  26808. return m.id === id;
  26809. });
  26810. };
  26811. /**
  26812. * Gets a mesh with its auto-generated unique id
  26813. * @param uniqueId defines the unique id to search for
  26814. * @return the found mesh or null if not found at all.
  26815. */
  26816. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26817. for (var index = 0; index < this.meshes.length; index++) {
  26818. if (this.meshes[index].uniqueId === uniqueId) {
  26819. return this.meshes[index];
  26820. }
  26821. }
  26822. return null;
  26823. };
  26824. /**
  26825. * Gets a the last added mesh using a given id
  26826. * @param id defines the id to search for
  26827. * @return the found mesh or null if not found at all.
  26828. */
  26829. Scene.prototype.getLastMeshByID = function (id) {
  26830. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26831. if (this.meshes[index].id === id) {
  26832. return this.meshes[index];
  26833. }
  26834. }
  26835. return null;
  26836. };
  26837. /**
  26838. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26839. * @param id defines the id to search for
  26840. * @return the found node or null if not found at all
  26841. */
  26842. Scene.prototype.getLastEntryByID = function (id) {
  26843. var index;
  26844. for (index = this.meshes.length - 1; index >= 0; index--) {
  26845. if (this.meshes[index].id === id) {
  26846. return this.meshes[index];
  26847. }
  26848. }
  26849. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26850. if (this.transformNodes[index].id === id) {
  26851. return this.transformNodes[index];
  26852. }
  26853. }
  26854. for (index = this.cameras.length - 1; index >= 0; index--) {
  26855. if (this.cameras[index].id === id) {
  26856. return this.cameras[index];
  26857. }
  26858. }
  26859. for (index = this.lights.length - 1; index >= 0; index--) {
  26860. if (this.lights[index].id === id) {
  26861. return this.lights[index];
  26862. }
  26863. }
  26864. return null;
  26865. };
  26866. /**
  26867. * Gets a node (Mesh, Camera, Light) using a given id
  26868. * @param id defines the id to search for
  26869. * @return the found node or null if not found at all
  26870. */
  26871. Scene.prototype.getNodeByID = function (id) {
  26872. var mesh = this.getMeshByID(id);
  26873. if (mesh) {
  26874. return mesh;
  26875. }
  26876. var light = this.getLightByID(id);
  26877. if (light) {
  26878. return light;
  26879. }
  26880. var camera = this.getCameraByID(id);
  26881. if (camera) {
  26882. return camera;
  26883. }
  26884. var bone = this.getBoneByID(id);
  26885. return bone;
  26886. };
  26887. /**
  26888. * Gets a node (Mesh, Camera, Light) using a given name
  26889. * @param name defines the name to search for
  26890. * @return the found node or null if not found at all.
  26891. */
  26892. Scene.prototype.getNodeByName = function (name) {
  26893. var mesh = this.getMeshByName(name);
  26894. if (mesh) {
  26895. return mesh;
  26896. }
  26897. var light = this.getLightByName(name);
  26898. if (light) {
  26899. return light;
  26900. }
  26901. var camera = this.getCameraByName(name);
  26902. if (camera) {
  26903. return camera;
  26904. }
  26905. var bone = this.getBoneByName(name);
  26906. return bone;
  26907. };
  26908. /**
  26909. * Gets a mesh using a given name
  26910. * @param name defines the name to search for
  26911. * @return the found mesh or null if not found at all.
  26912. */
  26913. Scene.prototype.getMeshByName = function (name) {
  26914. for (var index = 0; index < this.meshes.length; index++) {
  26915. if (this.meshes[index].name === name) {
  26916. return this.meshes[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a transform node using a given name
  26923. * @param name defines the name to search for
  26924. * @return the found transform node or null if not found at all.
  26925. */
  26926. Scene.prototype.getTransformNodeByName = function (name) {
  26927. for (var index = 0; index < this.transformNodes.length; index++) {
  26928. if (this.transformNodes[index].name === name) {
  26929. return this.transformNodes[index];
  26930. }
  26931. }
  26932. return null;
  26933. };
  26934. /**
  26935. * Gets a sound using a given name
  26936. * @param name defines the name to search for
  26937. * @return the found sound or null if not found at all.
  26938. */
  26939. Scene.prototype.getSoundByName = function (name) {
  26940. var index;
  26941. if (BABYLON.AudioEngine) {
  26942. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26943. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26944. return this.mainSoundTrack.soundCollection[index];
  26945. }
  26946. }
  26947. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26948. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26949. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26950. return this.soundTracks[sdIndex].soundCollection[index];
  26951. }
  26952. }
  26953. }
  26954. }
  26955. return null;
  26956. };
  26957. /**
  26958. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26959. * @param id defines the id to search for
  26960. * @return the found skeleton or null if not found at all.
  26961. */
  26962. Scene.prototype.getLastSkeletonByID = function (id) {
  26963. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26964. if (this.skeletons[index].id === id) {
  26965. return this.skeletons[index];
  26966. }
  26967. }
  26968. return null;
  26969. };
  26970. /**
  26971. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26972. * @param id defines the id to search for
  26973. * @return the found skeleton or null if not found at all.
  26974. */
  26975. Scene.prototype.getSkeletonById = function (id) {
  26976. for (var index = 0; index < this.skeletons.length; index++) {
  26977. if (this.skeletons[index].id === id) {
  26978. return this.skeletons[index];
  26979. }
  26980. }
  26981. return null;
  26982. };
  26983. /**
  26984. * Gets a skeleton using a given name
  26985. * @param name defines the name to search for
  26986. * @return the found skeleton or null if not found at all.
  26987. */
  26988. Scene.prototype.getSkeletonByName = function (name) {
  26989. for (var index = 0; index < this.skeletons.length; index++) {
  26990. if (this.skeletons[index].name === name) {
  26991. return this.skeletons[index];
  26992. }
  26993. }
  26994. return null;
  26995. };
  26996. /**
  26997. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26998. * @param id defines the id to search for
  26999. * @return the found morph target manager or null if not found at all.
  27000. */
  27001. Scene.prototype.getMorphTargetManagerById = function (id) {
  27002. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27003. if (this.morphTargetManagers[index].uniqueId === id) {
  27004. return this.morphTargetManagers[index];
  27005. }
  27006. }
  27007. return null;
  27008. };
  27009. /**
  27010. * Gets a boolean indicating if the given mesh is active
  27011. * @param mesh defines the mesh to look for
  27012. * @returns true if the mesh is in the active list
  27013. */
  27014. Scene.prototype.isActiveMesh = function (mesh) {
  27015. return (this._activeMeshes.indexOf(mesh) !== -1);
  27016. };
  27017. Object.defineProperty(Scene.prototype, "uid", {
  27018. /**
  27019. * Return a unique id as a string which can serve as an identifier for the scene
  27020. */
  27021. get: function () {
  27022. if (!this._uid) {
  27023. this._uid = BABYLON.Tools.RandomId();
  27024. }
  27025. return this._uid;
  27026. },
  27027. enumerable: true,
  27028. configurable: true
  27029. });
  27030. /**
  27031. * Add an externaly attached data from its key.
  27032. * This method call will fail and return false, if such key already exists.
  27033. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27034. * @param key the unique key that identifies the data
  27035. * @param data the data object to associate to the key for this Engine instance
  27036. * @return true if no such key were already present and the data was added successfully, false otherwise
  27037. */
  27038. Scene.prototype.addExternalData = function (key, data) {
  27039. if (!this._externalData) {
  27040. this._externalData = new BABYLON.StringDictionary();
  27041. }
  27042. return this._externalData.add(key, data);
  27043. };
  27044. /**
  27045. * Get an externaly attached data from its key
  27046. * @param key the unique key that identifies the data
  27047. * @return the associated data, if present (can be null), or undefined if not present
  27048. */
  27049. Scene.prototype.getExternalData = function (key) {
  27050. if (!this._externalData) {
  27051. return null;
  27052. }
  27053. return this._externalData.get(key);
  27054. };
  27055. /**
  27056. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27057. * @param key the unique key that identifies the data
  27058. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27059. * @return the associated data, can be null if the factory returned null.
  27060. */
  27061. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27062. if (!this._externalData) {
  27063. this._externalData = new BABYLON.StringDictionary();
  27064. }
  27065. return this._externalData.getOrAddWithFactory(key, factory);
  27066. };
  27067. /**
  27068. * Remove an externaly attached data from the Engine instance
  27069. * @param key the unique key that identifies the data
  27070. * @return true if the data was successfully removed, false if it doesn't exist
  27071. */
  27072. Scene.prototype.removeExternalData = function (key) {
  27073. return this._externalData.remove(key);
  27074. };
  27075. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27076. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27077. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27078. var step = _a[_i];
  27079. step.action(mesh, subMesh);
  27080. }
  27081. var material = subMesh.getMaterial();
  27082. if (material !== null && material !== undefined) {
  27083. // Render targets
  27084. if (material.getRenderTargetTextures !== undefined) {
  27085. if (this._processedMaterials.indexOf(material) === -1) {
  27086. this._processedMaterials.push(material);
  27087. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27088. }
  27089. }
  27090. // Dispatch
  27091. this._activeIndices.addCount(subMesh.indexCount, false);
  27092. this._renderingManager.dispatch(subMesh, mesh, material);
  27093. }
  27094. }
  27095. };
  27096. /**
  27097. * Clear the processed materials smart array preventing retention point in material dispose.
  27098. */
  27099. Scene.prototype.freeProcessedMaterials = function () {
  27100. this._processedMaterials.dispose();
  27101. };
  27102. /**
  27103. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27104. */
  27105. Scene.prototype.freeActiveMeshes = function () {
  27106. this._activeMeshes.dispose();
  27107. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27108. this.activeCamera._activeMeshes.dispose();
  27109. }
  27110. if (this.activeCameras) {
  27111. for (var i = 0; i < this.activeCameras.length; i++) {
  27112. var activeCamera = this.activeCameras[i];
  27113. if (activeCamera && activeCamera._activeMeshes) {
  27114. activeCamera._activeMeshes.dispose();
  27115. }
  27116. }
  27117. }
  27118. };
  27119. /**
  27120. * Clear the info related to rendering groups preventing retention points during dispose.
  27121. */
  27122. Scene.prototype.freeRenderingGroups = function () {
  27123. if (this._renderingManager) {
  27124. this._renderingManager.freeRenderingGroups();
  27125. }
  27126. if (this.textures) {
  27127. for (var i = 0; i < this.textures.length; i++) {
  27128. var texture = this.textures[i];
  27129. if (texture && texture.renderList) {
  27130. texture.freeRenderingGroups();
  27131. }
  27132. }
  27133. }
  27134. };
  27135. /** @hidden */
  27136. Scene.prototype._isInIntermediateRendering = function () {
  27137. return this._intermediateRendering;
  27138. };
  27139. /**
  27140. * Defines the current active mesh candidate provider
  27141. * @param provider defines the provider to use
  27142. */
  27143. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27144. this._activeMeshCandidateProvider = provider;
  27145. };
  27146. /**
  27147. * Gets the current active mesh candidate provider
  27148. * @returns the current active mesh candidate provider
  27149. */
  27150. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27151. return this._activeMeshCandidateProvider;
  27152. };
  27153. /**
  27154. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27155. * @returns the current scene
  27156. */
  27157. Scene.prototype.freezeActiveMeshes = function () {
  27158. if (!this.activeCamera) {
  27159. return this;
  27160. }
  27161. if (!this._frustumPlanes) {
  27162. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27163. }
  27164. this._evaluateActiveMeshes();
  27165. this._activeMeshesFrozen = true;
  27166. return this;
  27167. };
  27168. /**
  27169. * Use this function to restart evaluating active meshes on every frame
  27170. * @returns the current scene
  27171. */
  27172. Scene.prototype.unfreezeActiveMeshes = function () {
  27173. this._activeMeshesFrozen = false;
  27174. return this;
  27175. };
  27176. Scene.prototype._evaluateActiveMeshes = function () {
  27177. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27178. return;
  27179. }
  27180. if (!this.activeCamera) {
  27181. return;
  27182. }
  27183. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27184. this.activeCamera._activeMeshes.reset();
  27185. this._activeMeshes.reset();
  27186. this._renderingManager.reset();
  27187. this._processedMaterials.reset();
  27188. this._activeParticleSystems.reset();
  27189. this._activeSkeletons.reset();
  27190. this._softwareSkinnedMeshes.reset();
  27191. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27192. var step = _a[_i];
  27193. step.action();
  27194. }
  27195. // Meshes
  27196. var meshes;
  27197. var len;
  27198. var checkIsEnabled = true;
  27199. // Determine mesh candidates
  27200. if (this._activeMeshCandidateProvider !== undefined) {
  27201. // Use _activeMeshCandidateProvider
  27202. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27203. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27204. if (meshes !== undefined) {
  27205. len = meshes.length;
  27206. }
  27207. else {
  27208. len = 0;
  27209. }
  27210. }
  27211. else if (this._selectionOctree !== undefined) {
  27212. // Octree
  27213. var selection = this._selectionOctree.select(this._frustumPlanes);
  27214. meshes = selection.data;
  27215. len = selection.length;
  27216. }
  27217. else {
  27218. // Full scene traversal
  27219. len = this.meshes.length;
  27220. meshes = this.meshes;
  27221. }
  27222. // Check each mesh
  27223. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27224. mesh = meshes[meshIndex];
  27225. if (mesh.isBlocked) {
  27226. continue;
  27227. }
  27228. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27229. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27230. continue;
  27231. }
  27232. mesh.computeWorldMatrix();
  27233. // Intersections
  27234. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27235. this._meshesForIntersections.pushNoDuplicate(mesh);
  27236. }
  27237. // Switch to current LOD
  27238. meshLOD = mesh.getLOD(this.activeCamera);
  27239. if (meshLOD === undefined || meshLOD === null) {
  27240. continue;
  27241. }
  27242. mesh._preActivate();
  27243. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27244. this._activeMeshes.push(mesh);
  27245. this.activeCamera._activeMeshes.push(mesh);
  27246. mesh._activate(this._renderId);
  27247. if (meshLOD !== mesh) {
  27248. meshLOD._activate(this._renderId);
  27249. }
  27250. this._activeMesh(mesh, meshLOD);
  27251. }
  27252. }
  27253. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27254. // Particle systems
  27255. if (this.particlesEnabled) {
  27256. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27257. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27258. var particleSystem = this.particleSystems[particleIndex];
  27259. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27260. continue;
  27261. }
  27262. var emitter = particleSystem.emitter;
  27263. if (!emitter.position || emitter.isEnabled()) {
  27264. this._activeParticleSystems.push(particleSystem);
  27265. particleSystem.animate();
  27266. this._renderingManager.dispatchParticles(particleSystem);
  27267. }
  27268. }
  27269. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27270. }
  27271. };
  27272. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27273. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27274. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27275. mesh.skeleton.prepare();
  27276. }
  27277. if (!mesh.computeBonesUsingShaders) {
  27278. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27279. }
  27280. }
  27281. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27282. var step = _a[_i];
  27283. step.action(sourceMesh, mesh);
  27284. }
  27285. if (mesh !== undefined && mesh !== null
  27286. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27287. // Submeshes Octrees
  27288. var len;
  27289. var subMeshes;
  27290. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27291. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27292. len = intersections.length;
  27293. subMeshes = intersections.data;
  27294. }
  27295. else {
  27296. subMeshes = mesh.subMeshes;
  27297. len = subMeshes.length;
  27298. }
  27299. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27300. subMesh = subMeshes[subIndex];
  27301. this._evaluateSubMesh(subMesh, mesh);
  27302. }
  27303. }
  27304. };
  27305. /**
  27306. * Update the transform matrix to update from the current active camera
  27307. * @param force defines a boolean used to force the update even if cache is up to date
  27308. */
  27309. Scene.prototype.updateTransformMatrix = function (force) {
  27310. if (!this.activeCamera) {
  27311. return;
  27312. }
  27313. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27314. };
  27315. /**
  27316. * 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)
  27317. * @param alternateCamera defines the camera to use
  27318. */
  27319. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27320. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27321. };
  27322. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27323. if (camera && camera._skipRendering) {
  27324. return;
  27325. }
  27326. var engine = this._engine;
  27327. this.activeCamera = camera;
  27328. if (!this.activeCamera)
  27329. throw new Error("Active camera not set");
  27330. // Viewport
  27331. engine.setViewport(this.activeCamera.viewport);
  27332. // Camera
  27333. this.resetCachedMaterial();
  27334. this._renderId++;
  27335. this.updateTransformMatrix();
  27336. if (camera._alternateCamera) {
  27337. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27338. this._alternateRendering = true;
  27339. }
  27340. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27341. // Meshes
  27342. this._evaluateActiveMeshes();
  27343. // Software skinning
  27344. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27345. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27346. mesh.applySkeleton(mesh.skeleton);
  27347. }
  27348. // Render targets
  27349. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27350. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27351. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27352. }
  27353. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27354. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27355. }
  27356. if (this.renderTargetsEnabled) {
  27357. this._intermediateRendering = true;
  27358. if (this._renderTargets.length > 0) {
  27359. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27360. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27361. var renderTarget = this._renderTargets.data[renderIndex];
  27362. if (renderTarget._shouldRender()) {
  27363. this._renderId++;
  27364. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27365. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27366. }
  27367. }
  27368. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27369. this._renderId++;
  27370. }
  27371. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27372. var step = _a[_i];
  27373. step.action(this.activeCamera);
  27374. }
  27375. this._intermediateRendering = false;
  27376. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27377. }
  27378. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27379. // Prepare Frame
  27380. if (this.postProcessManager) {
  27381. this.postProcessManager._prepareFrame();
  27382. }
  27383. // Before Camera Draw
  27384. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27385. var step = _c[_b];
  27386. step.action(this.activeCamera);
  27387. }
  27388. // Render
  27389. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27390. this._renderingManager.render(null, null, true, true);
  27391. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27392. // After Camera Draw
  27393. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27394. var step = _e[_d];
  27395. step.action(this.activeCamera);
  27396. }
  27397. // Finalize frame
  27398. if (this.postProcessManager) {
  27399. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27400. }
  27401. // Reset some special arrays
  27402. this._renderTargets.reset();
  27403. this._alternateRendering = false;
  27404. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27405. };
  27406. Scene.prototype._processSubCameras = function (camera) {
  27407. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27408. this._renderForCamera(camera);
  27409. return;
  27410. }
  27411. // rig cameras
  27412. for (var index = 0; index < camera._rigCameras.length; index++) {
  27413. this._renderForCamera(camera._rigCameras[index], camera);
  27414. }
  27415. this.activeCamera = camera;
  27416. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27417. };
  27418. Scene.prototype._checkIntersections = function () {
  27419. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27420. var sourceMesh = this._meshesForIntersections.data[index];
  27421. if (!sourceMesh.actionManager) {
  27422. continue;
  27423. }
  27424. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27425. var action = sourceMesh.actionManager.actions[actionIndex];
  27426. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27427. var parameters = action.getTriggerParameter();
  27428. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27429. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27430. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27431. if (areIntersecting && currentIntersectionInProgress === -1) {
  27432. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27433. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27434. sourceMesh._intersectionsInProgress.push(otherMesh);
  27435. }
  27436. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27437. sourceMesh._intersectionsInProgress.push(otherMesh);
  27438. }
  27439. }
  27440. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27441. //They intersected, and now they don't.
  27442. //is this trigger an exit trigger? execute an event.
  27443. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27444. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27445. }
  27446. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27447. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27448. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27449. return otherMesh === parameterMesh;
  27450. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27451. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27452. }
  27453. }
  27454. }
  27455. }
  27456. }
  27457. };
  27458. /**
  27459. * Render the scene
  27460. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27461. */
  27462. Scene.prototype.render = function (updateCameras) {
  27463. if (updateCameras === void 0) { updateCameras = true; }
  27464. if (this.isDisposed) {
  27465. return;
  27466. }
  27467. // Register components that have been associated lately to the scene.
  27468. this._registerTransientComponents();
  27469. this._activeParticles.fetchNewFrame();
  27470. this._totalVertices.fetchNewFrame();
  27471. this._activeIndices.fetchNewFrame();
  27472. this._activeBones.fetchNewFrame();
  27473. this._meshesForIntersections.reset();
  27474. this.resetCachedMaterial();
  27475. this.onBeforeAnimationsObservable.notifyObservers(this);
  27476. // Actions
  27477. if (this.actionManager) {
  27478. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27479. }
  27480. //Simplification Queue
  27481. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27482. this.simplificationQueue.executeNext();
  27483. }
  27484. if (this._engine.isDeterministicLockStep()) {
  27485. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27486. var defaultFPS = (60.0 / 1000.0);
  27487. var defaultFrameTime = 1000 / 60; // frame time in MS
  27488. if (this._physicsEngine) {
  27489. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27490. }
  27491. var stepsTaken = 0;
  27492. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27493. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27494. internalSteps = Math.min(internalSteps, maxSubSteps);
  27495. do {
  27496. this.onBeforeStepObservable.notifyObservers(this);
  27497. // Animations
  27498. this._animationRatio = defaultFrameTime * defaultFPS;
  27499. this._animate();
  27500. this.onAfterAnimationsObservable.notifyObservers(this);
  27501. // Physics
  27502. if (this._physicsEngine) {
  27503. this.onBeforePhysicsObservable.notifyObservers(this);
  27504. this._physicsEngine._step(defaultFrameTime / 1000);
  27505. this.onAfterPhysicsObservable.notifyObservers(this);
  27506. }
  27507. this.onAfterStepObservable.notifyObservers(this);
  27508. this._currentStepId++;
  27509. stepsTaken++;
  27510. deltaTime -= defaultFrameTime;
  27511. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27512. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27513. }
  27514. else {
  27515. // Animations
  27516. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27517. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27518. this._animate();
  27519. this.onAfterAnimationsObservable.notifyObservers(this);
  27520. // Physics
  27521. if (this._physicsEngine) {
  27522. this.onBeforePhysicsObservable.notifyObservers(this);
  27523. this._physicsEngine._step(deltaTime / 1000.0);
  27524. this.onAfterPhysicsObservable.notifyObservers(this);
  27525. }
  27526. }
  27527. // Before camera update steps
  27528. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27529. var step = _a[_i];
  27530. step.action();
  27531. }
  27532. // Update Cameras
  27533. if (updateCameras) {
  27534. if (this.activeCameras.length > 0) {
  27535. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27536. var camera = this.activeCameras[cameraIndex];
  27537. camera.update();
  27538. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27539. // rig cameras
  27540. for (var index = 0; index < camera._rigCameras.length; index++) {
  27541. camera._rigCameras[index].update();
  27542. }
  27543. }
  27544. }
  27545. }
  27546. else if (this.activeCamera) {
  27547. this.activeCamera.update();
  27548. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27549. // rig cameras
  27550. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27551. this.activeCamera._rigCameras[index].update();
  27552. }
  27553. }
  27554. }
  27555. }
  27556. // Before render
  27557. this.onBeforeRenderObservable.notifyObservers(this);
  27558. // Customs render targets
  27559. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27560. var engine = this.getEngine();
  27561. var currentActiveCamera = this.activeCamera;
  27562. if (this.renderTargetsEnabled) {
  27563. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27564. this._intermediateRendering = true;
  27565. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27566. var renderTarget = this.customRenderTargets[customIndex];
  27567. if (renderTarget._shouldRender()) {
  27568. this._renderId++;
  27569. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27570. if (!this.activeCamera)
  27571. throw new Error("Active camera not set");
  27572. // Viewport
  27573. engine.setViewport(this.activeCamera.viewport);
  27574. // Camera
  27575. this.updateTransformMatrix();
  27576. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27577. }
  27578. }
  27579. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27580. this._intermediateRendering = false;
  27581. this._renderId++;
  27582. }
  27583. // Restore back buffer
  27584. if (this.customRenderTargets.length > 0) {
  27585. engine.restoreDefaultFramebuffer();
  27586. }
  27587. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27588. this.activeCamera = currentActiveCamera;
  27589. // Procedural textures
  27590. if (this.proceduralTexturesEnabled) {
  27591. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27592. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27593. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27594. if (proceduralTexture._shouldRender()) {
  27595. proceduralTexture.render();
  27596. }
  27597. }
  27598. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27599. }
  27600. // Clear
  27601. if (this.autoClearDepthAndStencil || this.autoClear) {
  27602. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27603. }
  27604. // Shadows
  27605. if (this.shadowsEnabled) {
  27606. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27607. var light = this.lights[lightIndex];
  27608. var shadowGenerator = light.getShadowGenerator();
  27609. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27610. var shadowMap = (shadowGenerator.getShadowMap());
  27611. if (this.textures.indexOf(shadowMap) !== -1) {
  27612. this._renderTargets.push(shadowMap);
  27613. }
  27614. }
  27615. }
  27616. }
  27617. // Depth renderer
  27618. for (var key in this._depthRenderer) {
  27619. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27620. }
  27621. // Geometry renderer
  27622. if (this._geometryBufferRenderer) {
  27623. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27624. }
  27625. // RenderPipeline
  27626. if (this._postProcessRenderPipelineManager) {
  27627. this._postProcessRenderPipelineManager.update();
  27628. }
  27629. // Multi-cameras?
  27630. if (this.activeCameras.length > 0) {
  27631. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27632. if (cameraIndex > 0) {
  27633. this._engine.clear(null, false, true, true);
  27634. }
  27635. this._processSubCameras(this.activeCameras[cameraIndex]);
  27636. }
  27637. }
  27638. else {
  27639. if (!this.activeCamera) {
  27640. throw new Error("No camera defined");
  27641. }
  27642. this._processSubCameras(this.activeCamera);
  27643. }
  27644. // Intersection checks
  27645. this._checkIntersections();
  27646. // Update the audio listener attached to the camera
  27647. if (BABYLON.AudioEngine) {
  27648. this._updateAudioParameters();
  27649. }
  27650. // After render
  27651. if (this.afterRender) {
  27652. this.afterRender();
  27653. }
  27654. this.onAfterRenderObservable.notifyObservers(this);
  27655. // Cleaning
  27656. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27657. var data = this._toBeDisposed.data[index];
  27658. if (data) {
  27659. data.dispose();
  27660. }
  27661. this._toBeDisposed[index] = null;
  27662. }
  27663. this._toBeDisposed.reset();
  27664. if (this.dumpNextRenderTargets) {
  27665. this.dumpNextRenderTargets = false;
  27666. }
  27667. this._activeBones.addCount(0, true);
  27668. this._activeIndices.addCount(0, true);
  27669. this._activeParticles.addCount(0, true);
  27670. };
  27671. Scene.prototype._updateAudioParameters = function () {
  27672. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27673. return;
  27674. }
  27675. var listeningCamera;
  27676. var audioEngine = BABYLON.Engine.audioEngine;
  27677. if (this.activeCameras.length > 0) {
  27678. listeningCamera = this.activeCameras[0];
  27679. }
  27680. else {
  27681. listeningCamera = this.activeCamera;
  27682. }
  27683. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27684. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27685. // for VR cameras
  27686. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27687. listeningCamera = listeningCamera.rigCameras[0];
  27688. }
  27689. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27690. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27691. cameraDirection.normalize();
  27692. // To avoid some errors on GearVR
  27693. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27694. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27695. }
  27696. var i;
  27697. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27698. var sound = this.mainSoundTrack.soundCollection[i];
  27699. if (sound.useCustomAttenuation) {
  27700. sound.updateDistanceFromListener();
  27701. }
  27702. }
  27703. for (i = 0; i < this.soundTracks.length; i++) {
  27704. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27705. sound = this.soundTracks[i].soundCollection[j];
  27706. if (sound.useCustomAttenuation) {
  27707. sound.updateDistanceFromListener();
  27708. }
  27709. }
  27710. }
  27711. }
  27712. };
  27713. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27714. // Audio
  27715. /**
  27716. * Gets or sets if audio support is enabled
  27717. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27718. */
  27719. get: function () {
  27720. return this._audioEnabled;
  27721. },
  27722. set: function (value) {
  27723. this._audioEnabled = value;
  27724. if (BABYLON.AudioEngine) {
  27725. if (this._audioEnabled) {
  27726. this._enableAudio();
  27727. }
  27728. else {
  27729. this._disableAudio();
  27730. }
  27731. }
  27732. },
  27733. enumerable: true,
  27734. configurable: true
  27735. });
  27736. Scene.prototype._disableAudio = function () {
  27737. var i;
  27738. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27739. this.mainSoundTrack.soundCollection[i].pause();
  27740. }
  27741. for (i = 0; i < this.soundTracks.length; i++) {
  27742. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27743. this.soundTracks[i].soundCollection[j].pause();
  27744. }
  27745. }
  27746. };
  27747. Scene.prototype._enableAudio = function () {
  27748. var i;
  27749. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27750. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27751. this.mainSoundTrack.soundCollection[i].play();
  27752. }
  27753. }
  27754. for (i = 0; i < this.soundTracks.length; i++) {
  27755. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27756. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27757. this.soundTracks[i].soundCollection[j].play();
  27758. }
  27759. }
  27760. }
  27761. };
  27762. Object.defineProperty(Scene.prototype, "headphone", {
  27763. /**
  27764. * Gets or sets if audio will be output to headphones
  27765. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27766. */
  27767. get: function () {
  27768. return this._headphone;
  27769. },
  27770. set: function (value) {
  27771. this._headphone = value;
  27772. if (BABYLON.AudioEngine) {
  27773. if (this._headphone) {
  27774. this._switchAudioModeForHeadphones();
  27775. }
  27776. else {
  27777. this._switchAudioModeForNormalSpeakers();
  27778. }
  27779. }
  27780. },
  27781. enumerable: true,
  27782. configurable: true
  27783. });
  27784. Scene.prototype._switchAudioModeForHeadphones = function () {
  27785. this.mainSoundTrack.switchPanningModelToHRTF();
  27786. for (var i = 0; i < this.soundTracks.length; i++) {
  27787. this.soundTracks[i].switchPanningModelToHRTF();
  27788. }
  27789. };
  27790. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27791. this.mainSoundTrack.switchPanningModelToEqualPower();
  27792. for (var i = 0; i < this.soundTracks.length; i++) {
  27793. this.soundTracks[i].switchPanningModelToEqualPower();
  27794. }
  27795. };
  27796. /**
  27797. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27798. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27799. * @returns the created depth renderer
  27800. */
  27801. Scene.prototype.enableDepthRenderer = function (camera) {
  27802. camera = camera || this.activeCamera;
  27803. if (!camera) {
  27804. throw "No camera available to enable depth renderer";
  27805. }
  27806. if (!this._depthRenderer[camera.id]) {
  27807. var textureType = 0;
  27808. if (this._engine.getCaps().textureHalfFloatRender) {
  27809. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27810. }
  27811. else if (this._engine.getCaps().textureFloatRender) {
  27812. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27813. }
  27814. else {
  27815. throw "Depth renderer does not support int texture type";
  27816. }
  27817. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27818. }
  27819. return this._depthRenderer[camera.id];
  27820. };
  27821. /**
  27822. * Disables a depth renderer for a given camera
  27823. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27824. */
  27825. Scene.prototype.disableDepthRenderer = function (camera) {
  27826. camera = camera || this.activeCamera;
  27827. if (!camera || !this._depthRenderer[camera.id]) {
  27828. return;
  27829. }
  27830. this._depthRenderer[camera.id].dispose();
  27831. delete this._depthRenderer[camera.id];
  27832. };
  27833. /**
  27834. * Enables a GeometryBufferRender and associates it with the scene
  27835. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27836. * @returns the GeometryBufferRenderer
  27837. */
  27838. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27839. if (ratio === void 0) { ratio = 1; }
  27840. if (this._geometryBufferRenderer) {
  27841. return this._geometryBufferRenderer;
  27842. }
  27843. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27844. if (!this._geometryBufferRenderer.isSupported) {
  27845. this._geometryBufferRenderer = null;
  27846. }
  27847. return this._geometryBufferRenderer;
  27848. };
  27849. /**
  27850. * Disables the GeometryBufferRender associated with the scene
  27851. */
  27852. Scene.prototype.disableGeometryBufferRenderer = function () {
  27853. if (!this._geometryBufferRenderer) {
  27854. return;
  27855. }
  27856. this._geometryBufferRenderer.dispose();
  27857. this._geometryBufferRenderer = null;
  27858. };
  27859. /**
  27860. * Freeze all materials
  27861. * A frozen material will not be updatable but should be faster to render
  27862. */
  27863. Scene.prototype.freezeMaterials = function () {
  27864. for (var i = 0; i < this.materials.length; i++) {
  27865. this.materials[i].freeze();
  27866. }
  27867. };
  27868. /**
  27869. * Unfreeze all materials
  27870. * A frozen material will not be updatable but should be faster to render
  27871. */
  27872. Scene.prototype.unfreezeMaterials = function () {
  27873. for (var i = 0; i < this.materials.length; i++) {
  27874. this.materials[i].unfreeze();
  27875. }
  27876. };
  27877. /**
  27878. * Releases all held ressources
  27879. */
  27880. Scene.prototype.dispose = function () {
  27881. this.beforeRender = null;
  27882. this.afterRender = null;
  27883. this.skeletons = [];
  27884. this.morphTargetManagers = [];
  27885. this._transientComponents = [];
  27886. this._isReadyForMeshStage.clear();
  27887. this._beforeEvaluateActiveMeshStage.clear();
  27888. this._evaluateSubMeshStage.clear();
  27889. this._activeMeshStage.clear();
  27890. this._cameraDrawRenderTargetStage.clear();
  27891. this._beforeCameraDrawStage.clear();
  27892. this._beforeRenderingGroupDrawStage.clear();
  27893. this._afterRenderingGroupDrawStage.clear();
  27894. this._afterCameraDrawStage.clear();
  27895. this._beforeCameraUpdateStage.clear();
  27896. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27897. var component = _a[_i];
  27898. component.dispose();
  27899. }
  27900. this.importedMeshesFiles = new Array();
  27901. this.stopAllAnimations();
  27902. this.resetCachedMaterial();
  27903. for (var key in this._depthRenderer) {
  27904. this._depthRenderer[key].dispose();
  27905. }
  27906. // Smart arrays
  27907. if (this.activeCamera) {
  27908. this.activeCamera._activeMeshes.dispose();
  27909. this.activeCamera = null;
  27910. }
  27911. this._activeMeshes.dispose();
  27912. this._renderingManager.dispose();
  27913. this._processedMaterials.dispose();
  27914. this._activeParticleSystems.dispose();
  27915. this._activeSkeletons.dispose();
  27916. this._softwareSkinnedMeshes.dispose();
  27917. this._renderTargets.dispose();
  27918. this._registeredForLateAnimationBindings.dispose();
  27919. this._meshesForIntersections.dispose();
  27920. this._toBeDisposed.dispose();
  27921. // Abort active requests
  27922. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27923. var request = _c[_b];
  27924. request.abort();
  27925. }
  27926. // Debug layer
  27927. if (this._debugLayer) {
  27928. this._debugLayer.hide();
  27929. }
  27930. // Events
  27931. this.onDisposeObservable.notifyObservers(this);
  27932. this.onDisposeObservable.clear();
  27933. this.onBeforeRenderObservable.clear();
  27934. this.onAfterRenderObservable.clear();
  27935. this.onBeforeRenderTargetsRenderObservable.clear();
  27936. this.onAfterRenderTargetsRenderObservable.clear();
  27937. this.onAfterStepObservable.clear();
  27938. this.onBeforeStepObservable.clear();
  27939. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27940. this.onAfterActiveMeshesEvaluationObservable.clear();
  27941. this.onBeforeParticlesRenderingObservable.clear();
  27942. this.onAfterParticlesRenderingObservable.clear();
  27943. this.onBeforeSpritesRenderingObservable.clear();
  27944. this.onAfterSpritesRenderingObservable.clear();
  27945. this.onBeforeDrawPhaseObservable.clear();
  27946. this.onAfterDrawPhaseObservable.clear();
  27947. this.onBeforePhysicsObservable.clear();
  27948. this.onAfterPhysicsObservable.clear();
  27949. this.onBeforeAnimationsObservable.clear();
  27950. this.onAfterAnimationsObservable.clear();
  27951. this.onDataLoadedObservable.clear();
  27952. this.detachControl();
  27953. // Release sounds & sounds tracks
  27954. if (BABYLON.AudioEngine) {
  27955. this.disposeSounds();
  27956. }
  27957. // VR Helper
  27958. if (this.VRHelper) {
  27959. this.VRHelper.dispose();
  27960. }
  27961. // Detach cameras
  27962. var canvas = this._engine.getRenderingCanvas();
  27963. if (canvas) {
  27964. var index;
  27965. for (index = 0; index < this.cameras.length; index++) {
  27966. this.cameras[index].detachControl(canvas);
  27967. }
  27968. }
  27969. // Release animation groups
  27970. while (this.animationGroups.length) {
  27971. this.animationGroups[0].dispose();
  27972. }
  27973. // Release lights
  27974. while (this.lights.length) {
  27975. this.lights[0].dispose();
  27976. }
  27977. // Release meshes
  27978. while (this.meshes.length) {
  27979. this.meshes[0].dispose(true);
  27980. }
  27981. while (this.transformNodes.length) {
  27982. this.removeTransformNode(this.transformNodes[0]);
  27983. }
  27984. // Release cameras
  27985. while (this.cameras.length) {
  27986. this.cameras[0].dispose();
  27987. }
  27988. // Release materials
  27989. if (this.defaultMaterial) {
  27990. this.defaultMaterial.dispose();
  27991. }
  27992. while (this.multiMaterials.length) {
  27993. this.multiMaterials[0].dispose();
  27994. }
  27995. while (this.materials.length) {
  27996. this.materials[0].dispose();
  27997. }
  27998. // Release particles
  27999. while (this.particleSystems.length) {
  28000. this.particleSystems[0].dispose();
  28001. }
  28002. // Release sprites
  28003. while (this.spriteManagers.length) {
  28004. this.spriteManagers[0].dispose();
  28005. }
  28006. // Release postProcesses
  28007. while (this.postProcesses.length) {
  28008. this.postProcesses[0].dispose();
  28009. }
  28010. // Release textures
  28011. while (this.textures.length) {
  28012. this.textures[0].dispose();
  28013. }
  28014. // Release UBO
  28015. this._sceneUbo.dispose();
  28016. if (this._alternateSceneUbo) {
  28017. this._alternateSceneUbo.dispose();
  28018. }
  28019. // Post-processes
  28020. this.postProcessManager.dispose();
  28021. if (this._postProcessRenderPipelineManager) {
  28022. this._postProcessRenderPipelineManager.dispose();
  28023. }
  28024. // Physics
  28025. if (this._physicsEngine) {
  28026. this.disablePhysicsEngine();
  28027. }
  28028. // Remove from engine
  28029. index = this._engine.scenes.indexOf(this);
  28030. if (index > -1) {
  28031. this._engine.scenes.splice(index, 1);
  28032. }
  28033. this._engine.wipeCaches(true);
  28034. this._isDisposed = true;
  28035. };
  28036. Object.defineProperty(Scene.prototype, "isDisposed", {
  28037. /**
  28038. * Gets if the scene is already disposed
  28039. */
  28040. get: function () {
  28041. return this._isDisposed;
  28042. },
  28043. enumerable: true,
  28044. configurable: true
  28045. });
  28046. /**
  28047. * Releases sounds & soundtracks
  28048. */
  28049. Scene.prototype.disposeSounds = function () {
  28050. if (!this._mainSoundTrack) {
  28051. return;
  28052. }
  28053. this.mainSoundTrack.dispose();
  28054. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28055. this.soundTracks[scIndex].dispose();
  28056. }
  28057. };
  28058. /**
  28059. * Call this function to reduce memory footprint of the scene.
  28060. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28061. */
  28062. Scene.prototype.clearCachedVertexData = function () {
  28063. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28064. var mesh = this.meshes[meshIndex];
  28065. var geometry = mesh.geometry;
  28066. if (geometry) {
  28067. geometry._indices = [];
  28068. for (var vbName in geometry._vertexBuffers) {
  28069. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28070. continue;
  28071. }
  28072. geometry._vertexBuffers[vbName]._buffer._data = null;
  28073. }
  28074. }
  28075. }
  28076. };
  28077. /**
  28078. * This function will remove the local cached buffer data from texture.
  28079. * It will save memory but will prevent the texture from being rebuilt
  28080. */
  28081. Scene.prototype.cleanCachedTextureBuffer = function () {
  28082. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28083. var baseTexture = _a[_i];
  28084. var buffer = baseTexture._buffer;
  28085. if (buffer) {
  28086. baseTexture._buffer = null;
  28087. }
  28088. }
  28089. };
  28090. // Octrees
  28091. /**
  28092. * Get the world extend vectors with an optional filter
  28093. *
  28094. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28095. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28096. */
  28097. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28098. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28099. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28100. filterPredicate = filterPredicate || (function () { return true; });
  28101. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28102. mesh.computeWorldMatrix(true);
  28103. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28104. return;
  28105. }
  28106. var boundingInfo = mesh.getBoundingInfo();
  28107. var minBox = boundingInfo.boundingBox.minimumWorld;
  28108. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28109. BABYLON.Tools.CheckExtends(minBox, min, max);
  28110. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28111. });
  28112. return {
  28113. min: min,
  28114. max: max
  28115. };
  28116. };
  28117. /**
  28118. * Creates or updates the octree used to boost selection (picking)
  28119. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28120. * @param maxCapacity defines the maximum capacity per leaf
  28121. * @param maxDepth defines the maximum depth of the octree
  28122. * @returns an octree of AbstractMesh
  28123. */
  28124. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28125. if (maxCapacity === void 0) { maxCapacity = 64; }
  28126. if (maxDepth === void 0) { maxDepth = 2; }
  28127. if (!this._selectionOctree) {
  28128. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28129. }
  28130. var worldExtends = this.getWorldExtends();
  28131. // Update octree
  28132. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28133. return this._selectionOctree;
  28134. };
  28135. // Picking
  28136. /**
  28137. * Creates a ray that can be used to pick in the scene
  28138. * @param x defines the x coordinate of the origin (on-screen)
  28139. * @param y defines the y coordinate of the origin (on-screen)
  28140. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28141. * @param camera defines the camera to use for the picking
  28142. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28143. * @returns a Ray
  28144. */
  28145. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28146. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28147. var result = BABYLON.Ray.Zero();
  28148. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28149. return result;
  28150. };
  28151. /**
  28152. * Creates a ray that can be used to pick in the scene
  28153. * @param x defines the x coordinate of the origin (on-screen)
  28154. * @param y defines the y coordinate of the origin (on-screen)
  28155. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28156. * @param result defines the ray where to store the picking ray
  28157. * @param camera defines the camera to use for the picking
  28158. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28159. * @returns the current scene
  28160. */
  28161. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28162. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28163. var engine = this._engine;
  28164. if (!camera) {
  28165. if (!this.activeCamera)
  28166. throw new Error("Active camera not set");
  28167. camera = this.activeCamera;
  28168. }
  28169. var cameraViewport = camera.viewport;
  28170. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28171. // Moving coordinates to local viewport world
  28172. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28173. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28174. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28175. return this;
  28176. };
  28177. /**
  28178. * Creates a ray that can be used to pick in the scene
  28179. * @param x defines the x coordinate of the origin (on-screen)
  28180. * @param y defines the y coordinate of the origin (on-screen)
  28181. * @param camera defines the camera to use for the picking
  28182. * @returns a Ray
  28183. */
  28184. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28185. var result = BABYLON.Ray.Zero();
  28186. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28187. return result;
  28188. };
  28189. /**
  28190. * Creates a ray that can be used to pick in the scene
  28191. * @param x defines the x coordinate of the origin (on-screen)
  28192. * @param y defines the y coordinate of the origin (on-screen)
  28193. * @param result defines the ray where to store the picking ray
  28194. * @param camera defines the camera to use for the picking
  28195. * @returns the current scene
  28196. */
  28197. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28198. if (!BABYLON.PickingInfo) {
  28199. return this;
  28200. }
  28201. var engine = this._engine;
  28202. if (!camera) {
  28203. if (!this.activeCamera)
  28204. throw new Error("Active camera not set");
  28205. camera = this.activeCamera;
  28206. }
  28207. var cameraViewport = camera.viewport;
  28208. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28209. var identity = BABYLON.Matrix.Identity();
  28210. // Moving coordinates to local viewport world
  28211. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28212. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28213. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28214. return this;
  28215. };
  28216. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28217. if (!BABYLON.PickingInfo) {
  28218. return null;
  28219. }
  28220. var pickingInfo = null;
  28221. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28222. var mesh = this.meshes[meshIndex];
  28223. if (predicate) {
  28224. if (!predicate(mesh)) {
  28225. continue;
  28226. }
  28227. }
  28228. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28229. continue;
  28230. }
  28231. var world = mesh.getWorldMatrix();
  28232. var ray = rayFunction(world);
  28233. var result = mesh.intersects(ray, fastCheck);
  28234. if (!result || !result.hit)
  28235. continue;
  28236. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28237. continue;
  28238. pickingInfo = result;
  28239. if (fastCheck) {
  28240. break;
  28241. }
  28242. }
  28243. return pickingInfo || new BABYLON.PickingInfo();
  28244. };
  28245. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28246. if (!BABYLON.PickingInfo) {
  28247. return null;
  28248. }
  28249. var pickingInfos = new Array();
  28250. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28251. var mesh = this.meshes[meshIndex];
  28252. if (predicate) {
  28253. if (!predicate(mesh)) {
  28254. continue;
  28255. }
  28256. }
  28257. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28258. continue;
  28259. }
  28260. var world = mesh.getWorldMatrix();
  28261. var ray = rayFunction(world);
  28262. var result = mesh.intersects(ray, false);
  28263. if (!result || !result.hit)
  28264. continue;
  28265. pickingInfos.push(result);
  28266. }
  28267. return pickingInfos;
  28268. };
  28269. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28270. if (!BABYLON.PickingInfo) {
  28271. return null;
  28272. }
  28273. var pickingInfo = null;
  28274. if (!camera) {
  28275. if (!this.activeCamera) {
  28276. return null;
  28277. }
  28278. camera = this.activeCamera;
  28279. }
  28280. if (this.spriteManagers.length > 0) {
  28281. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28282. var spriteManager = this.spriteManagers[spriteIndex];
  28283. if (!spriteManager.isPickable) {
  28284. continue;
  28285. }
  28286. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28287. if (!result || !result.hit)
  28288. continue;
  28289. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28290. continue;
  28291. pickingInfo = result;
  28292. if (fastCheck) {
  28293. break;
  28294. }
  28295. }
  28296. }
  28297. return pickingInfo || new BABYLON.PickingInfo();
  28298. };
  28299. /** Launch a ray to try to pick a mesh in the scene
  28300. * @param x position on screen
  28301. * @param y position on screen
  28302. * @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
  28303. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28304. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28305. * @returns a PickingInfo
  28306. */
  28307. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28308. var _this = this;
  28309. if (!BABYLON.PickingInfo) {
  28310. return null;
  28311. }
  28312. var result = this._internalPick(function (world) {
  28313. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28314. return _this._tempPickingRay;
  28315. }, predicate, fastCheck);
  28316. if (result) {
  28317. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28318. }
  28319. return result;
  28320. };
  28321. /** Launch a ray to try to pick a sprite in the scene
  28322. * @param x position on screen
  28323. * @param y position on screen
  28324. * @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
  28325. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28326. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28327. * @returns a PickingInfo
  28328. */
  28329. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28330. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28331. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28332. };
  28333. /** Use the given ray to pick a mesh in the scene
  28334. * @param ray The ray to use to pick meshes
  28335. * @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
  28336. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28337. * @returns a PickingInfo
  28338. */
  28339. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28340. var _this = this;
  28341. var result = this._internalPick(function (world) {
  28342. if (!_this._pickWithRayInverseMatrix) {
  28343. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28344. }
  28345. world.invertToRef(_this._pickWithRayInverseMatrix);
  28346. if (!_this._cachedRayForTransform) {
  28347. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28348. }
  28349. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28350. return _this._cachedRayForTransform;
  28351. }, predicate, fastCheck);
  28352. if (result) {
  28353. result.ray = ray;
  28354. }
  28355. return result;
  28356. };
  28357. /**
  28358. * Launch a ray to try to pick a mesh in the scene
  28359. * @param x X position on screen
  28360. * @param y Y position on screen
  28361. * @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
  28362. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28363. * @returns an array of PickingInfo
  28364. */
  28365. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28366. var _this = this;
  28367. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28368. };
  28369. /**
  28370. * Launch a ray to try to pick a mesh in the scene
  28371. * @param ray Ray to use
  28372. * @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
  28373. * @returns an array of PickingInfo
  28374. */
  28375. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28376. var _this = this;
  28377. return this._internalMultiPick(function (world) {
  28378. if (!_this._pickWithRayInverseMatrix) {
  28379. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28380. }
  28381. world.invertToRef(_this._pickWithRayInverseMatrix);
  28382. if (!_this._cachedRayForTransform) {
  28383. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28384. }
  28385. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28386. return _this._cachedRayForTransform;
  28387. }, predicate);
  28388. };
  28389. /**
  28390. * Force the value of meshUnderPointer
  28391. * @param mesh defines the mesh to use
  28392. */
  28393. Scene.prototype.setPointerOverMesh = function (mesh) {
  28394. if (this._pointerOverMesh === mesh) {
  28395. return;
  28396. }
  28397. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28398. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28399. }
  28400. this._pointerOverMesh = mesh;
  28401. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28402. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28403. }
  28404. };
  28405. /**
  28406. * Gets the mesh under the pointer
  28407. * @returns a Mesh or null if no mesh is under the pointer
  28408. */
  28409. Scene.prototype.getPointerOverMesh = function () {
  28410. return this._pointerOverMesh;
  28411. };
  28412. /**
  28413. * Force the sprite under the pointer
  28414. * @param sprite defines the sprite to use
  28415. */
  28416. Scene.prototype.setPointerOverSprite = function (sprite) {
  28417. if (this._pointerOverSprite === sprite) {
  28418. return;
  28419. }
  28420. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28421. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28422. }
  28423. this._pointerOverSprite = sprite;
  28424. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28425. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28426. }
  28427. };
  28428. /**
  28429. * Gets the sprite under the pointer
  28430. * @returns a Sprite or null if no sprite is under the pointer
  28431. */
  28432. Scene.prototype.getPointerOverSprite = function () {
  28433. return this._pointerOverSprite;
  28434. };
  28435. // Physics
  28436. /**
  28437. * Gets the current physics engine
  28438. * @returns a PhysicsEngine or null if none attached
  28439. */
  28440. Scene.prototype.getPhysicsEngine = function () {
  28441. return this._physicsEngine;
  28442. };
  28443. /**
  28444. * Enables physics to the current scene
  28445. * @param gravity defines the scene's gravity for the physics engine
  28446. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28447. * @return a boolean indicating if the physics engine was initialized
  28448. */
  28449. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28450. if (gravity === void 0) { gravity = null; }
  28451. if (this._physicsEngine) {
  28452. return true;
  28453. }
  28454. try {
  28455. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28456. return true;
  28457. }
  28458. catch (e) {
  28459. BABYLON.Tools.Error(e.message);
  28460. return false;
  28461. }
  28462. };
  28463. /**
  28464. * Disables and disposes the physics engine associated with the scene
  28465. */
  28466. Scene.prototype.disablePhysicsEngine = function () {
  28467. if (!this._physicsEngine) {
  28468. return;
  28469. }
  28470. this._physicsEngine.dispose();
  28471. this._physicsEngine = null;
  28472. };
  28473. /**
  28474. * Gets a boolean indicating if there is an active physics engine
  28475. * @returns a boolean indicating if there is an active physics engine
  28476. */
  28477. Scene.prototype.isPhysicsEnabled = function () {
  28478. return this._physicsEngine !== undefined;
  28479. };
  28480. /**
  28481. * Deletes a physics compound impostor
  28482. * @param compound defines the compound to delete
  28483. */
  28484. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28485. var mesh = compound.parts[0].mesh;
  28486. if (mesh.physicsImpostor) {
  28487. mesh.physicsImpostor.dispose( /*true*/);
  28488. mesh.physicsImpostor = null;
  28489. }
  28490. };
  28491. // Misc.
  28492. /** @hidden */
  28493. Scene.prototype._rebuildGeometries = function () {
  28494. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28495. var geometry = _a[_i];
  28496. geometry._rebuild();
  28497. }
  28498. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28499. var mesh = _c[_b];
  28500. mesh._rebuild();
  28501. }
  28502. if (this.postProcessManager) {
  28503. this.postProcessManager._rebuild();
  28504. }
  28505. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28506. var component = _e[_d];
  28507. component.rebuild();
  28508. }
  28509. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28510. var system = _g[_f];
  28511. system.rebuild();
  28512. }
  28513. if (this._postProcessRenderPipelineManager) {
  28514. this._postProcessRenderPipelineManager._rebuild();
  28515. }
  28516. };
  28517. /** @hidden */
  28518. Scene.prototype._rebuildTextures = function () {
  28519. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28520. var texture = _a[_i];
  28521. texture._rebuild();
  28522. }
  28523. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28524. };
  28525. /**
  28526. * Creates a default light for the scene.
  28527. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28528. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28529. */
  28530. Scene.prototype.createDefaultLight = function (replace) {
  28531. if (replace === void 0) { replace = false; }
  28532. // Dispose existing light in replace mode.
  28533. if (replace) {
  28534. if (this.lights) {
  28535. for (var i = 0; i < this.lights.length; i++) {
  28536. this.lights[i].dispose();
  28537. }
  28538. }
  28539. }
  28540. // Light
  28541. if (this.lights.length === 0) {
  28542. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28543. }
  28544. };
  28545. /**
  28546. * Creates a default camera for the scene.
  28547. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28548. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28549. * @param replace has default false, when true replaces the active camera in the scene
  28550. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28551. */
  28552. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28553. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28554. if (replace === void 0) { replace = false; }
  28555. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28556. // Dispose existing camera in replace mode.
  28557. if (replace) {
  28558. if (this.activeCamera) {
  28559. this.activeCamera.dispose();
  28560. this.activeCamera = null;
  28561. }
  28562. }
  28563. // Camera
  28564. if (!this.activeCamera) {
  28565. var worldExtends = this.getWorldExtends();
  28566. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28567. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28568. var camera;
  28569. var radius = worldSize.length() * 1.5;
  28570. // empty scene scenario!
  28571. if (!isFinite(radius)) {
  28572. radius = 1;
  28573. worldCenter.copyFromFloats(0, 0, 0);
  28574. }
  28575. if (createArcRotateCamera) {
  28576. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28577. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28578. arcRotateCamera.wheelPrecision = 100 / radius;
  28579. camera = arcRotateCamera;
  28580. }
  28581. else {
  28582. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28583. freeCamera.setTarget(worldCenter);
  28584. camera = freeCamera;
  28585. }
  28586. camera.minZ = radius * 0.01;
  28587. camera.maxZ = radius * 1000;
  28588. camera.speed = radius * 0.2;
  28589. this.activeCamera = camera;
  28590. var canvas = this.getEngine().getRenderingCanvas();
  28591. if (attachCameraControls && canvas) {
  28592. camera.attachControl(canvas);
  28593. }
  28594. }
  28595. };
  28596. /**
  28597. * Creates a default camera and a default light.
  28598. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28599. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28600. * @param replace has the default false, when true replaces the active camera/light in the scene
  28601. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28602. */
  28603. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28604. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28605. if (replace === void 0) { replace = false; }
  28606. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28607. this.createDefaultLight(replace);
  28608. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28609. };
  28610. /**
  28611. * Creates a new sky box
  28612. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28613. * @param environmentTexture defines the texture to use as environment texture
  28614. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28615. * @param scale defines the overall scale of the skybox
  28616. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28617. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28618. * @returns a new mesh holding the sky box
  28619. */
  28620. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28621. if (pbr === void 0) { pbr = false; }
  28622. if (scale === void 0) { scale = 1000; }
  28623. if (blur === void 0) { blur = 0; }
  28624. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28625. if (!environmentTexture) {
  28626. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28627. return null;
  28628. }
  28629. if (setGlobalEnvTexture) {
  28630. if (environmentTexture) {
  28631. this.environmentTexture = environmentTexture;
  28632. }
  28633. }
  28634. // Skybox
  28635. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28636. if (pbr) {
  28637. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28638. hdrSkyboxMaterial.backFaceCulling = false;
  28639. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28640. if (hdrSkyboxMaterial.reflectionTexture) {
  28641. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28642. }
  28643. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28644. hdrSkyboxMaterial.disableLighting = true;
  28645. hdrSkyboxMaterial.twoSidedLighting = true;
  28646. hdrSkybox.infiniteDistance = true;
  28647. hdrSkybox.material = hdrSkyboxMaterial;
  28648. }
  28649. else {
  28650. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28651. skyboxMaterial.backFaceCulling = false;
  28652. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28653. if (skyboxMaterial.reflectionTexture) {
  28654. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28655. }
  28656. skyboxMaterial.disableLighting = true;
  28657. hdrSkybox.infiniteDistance = true;
  28658. hdrSkybox.material = skyboxMaterial;
  28659. }
  28660. return hdrSkybox;
  28661. };
  28662. /**
  28663. * Creates a new environment
  28664. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28665. * @param options defines the options you can use to configure the environment
  28666. * @returns the new EnvironmentHelper
  28667. */
  28668. Scene.prototype.createDefaultEnvironment = function (options) {
  28669. if (BABYLON.EnvironmentHelper) {
  28670. return new BABYLON.EnvironmentHelper(options, this);
  28671. }
  28672. return null;
  28673. };
  28674. /**
  28675. * Creates a new VREXperienceHelper
  28676. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28677. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28678. * @returns a new VREXperienceHelper
  28679. */
  28680. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28681. if (webVROptions === void 0) { webVROptions = {}; }
  28682. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28683. };
  28684. // Tags
  28685. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28686. if (tagsQuery === undefined) {
  28687. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28688. return list;
  28689. }
  28690. var listByTags = [];
  28691. forEach = forEach || (function (item) { return; });
  28692. for (var i in list) {
  28693. var item = list[i];
  28694. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28695. listByTags.push(item);
  28696. forEach(item);
  28697. }
  28698. }
  28699. return listByTags;
  28700. };
  28701. /**
  28702. * Get a list of meshes by tags
  28703. * @param tagsQuery defines the tags query to use
  28704. * @param forEach defines a predicate used to filter results
  28705. * @returns an array of Mesh
  28706. */
  28707. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28708. return this._getByTags(this.meshes, tagsQuery, forEach);
  28709. };
  28710. /**
  28711. * Get a list of cameras by tags
  28712. * @param tagsQuery defines the tags query to use
  28713. * @param forEach defines a predicate used to filter results
  28714. * @returns an array of Camera
  28715. */
  28716. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28717. return this._getByTags(this.cameras, tagsQuery, forEach);
  28718. };
  28719. /**
  28720. * Get a list of lights by tags
  28721. * @param tagsQuery defines the tags query to use
  28722. * @param forEach defines a predicate used to filter results
  28723. * @returns an array of Light
  28724. */
  28725. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28726. return this._getByTags(this.lights, tagsQuery, forEach);
  28727. };
  28728. /**
  28729. * Get a list of materials by tags
  28730. * @param tagsQuery defines the tags query to use
  28731. * @param forEach defines a predicate used to filter results
  28732. * @returns an array of Material
  28733. */
  28734. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28735. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28736. };
  28737. /**
  28738. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28739. * This allowed control for front to back rendering or reversly depending of the special needs.
  28740. *
  28741. * @param renderingGroupId The rendering group id corresponding to its index
  28742. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28743. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28744. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28745. */
  28746. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28747. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28748. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28749. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28750. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28751. };
  28752. /**
  28753. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28754. *
  28755. * @param renderingGroupId The rendering group id corresponding to its index
  28756. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28757. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28758. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28759. */
  28760. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28761. if (depth === void 0) { depth = true; }
  28762. if (stencil === void 0) { stencil = true; }
  28763. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28764. };
  28765. /**
  28766. * Will flag all materials as dirty to trigger new shader compilation
  28767. * @param flag defines the flag used to specify which material part must be marked as dirty
  28768. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28769. */
  28770. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28771. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28772. var material = _a[_i];
  28773. if (predicate && !predicate(material)) {
  28774. continue;
  28775. }
  28776. material.markAsDirty(flag);
  28777. }
  28778. };
  28779. /** @hidden */
  28780. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28781. var _this = this;
  28782. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28783. this._activeRequests.push(request);
  28784. request.onCompleteObservable.add(function (request) {
  28785. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28786. });
  28787. return request;
  28788. };
  28789. /** @hidden */
  28790. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28791. var _this = this;
  28792. return new Promise(function (resolve, reject) {
  28793. _this._loadFile(url, function (data) {
  28794. resolve(data);
  28795. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28796. reject(exception);
  28797. });
  28798. });
  28799. };
  28800. // Statics
  28801. Scene._FOGMODE_NONE = 0;
  28802. Scene._FOGMODE_EXP = 1;
  28803. Scene._FOGMODE_EXP2 = 2;
  28804. Scene._FOGMODE_LINEAR = 3;
  28805. Scene._uniqueIdCounter = 0;
  28806. /**
  28807. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28808. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28809. */
  28810. Scene.MinDeltaTime = 1.0;
  28811. /**
  28812. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28813. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28814. */
  28815. Scene.MaxDeltaTime = 1000.0;
  28816. /** The distance in pixel that you have to move to prevent some events */
  28817. Scene.DragMovementThreshold = 10; // in pixels
  28818. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28819. Scene.LongPressDelay = 500; // in milliseconds
  28820. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28821. Scene.DoubleClickDelay = 300; // in milliseconds
  28822. /** If you need to check double click without raising a single click at first click, enable this flag */
  28823. Scene.ExclusiveDoubleClickMode = false;
  28824. return Scene;
  28825. }(BABYLON.AbstractScene));
  28826. BABYLON.Scene = Scene;
  28827. })(BABYLON || (BABYLON = {}));
  28828. //# sourceMappingURL=babylon.scene.js.map
  28829. var BABYLON;
  28830. (function (BABYLON) {
  28831. /**
  28832. * Set of assets to keep when moving a scene into an asset container.
  28833. */
  28834. var KeepAssets = /** @class */ (function (_super) {
  28835. __extends(KeepAssets, _super);
  28836. function KeepAssets() {
  28837. return _super !== null && _super.apply(this, arguments) || this;
  28838. }
  28839. return KeepAssets;
  28840. }(BABYLON.AbstractScene));
  28841. BABYLON.KeepAssets = KeepAssets;
  28842. /**
  28843. * Container with a set of assets that can be added or removed from a scene.
  28844. */
  28845. var AssetContainer = /** @class */ (function (_super) {
  28846. __extends(AssetContainer, _super);
  28847. /**
  28848. * Instantiates an AssetContainer.
  28849. * @param scene The scene the AssetContainer belongs to.
  28850. */
  28851. function AssetContainer(scene) {
  28852. var _this = _super.call(this) || this;
  28853. _this.scene = scene;
  28854. return _this;
  28855. }
  28856. /**
  28857. * Adds all the assets from the container to the scene.
  28858. */
  28859. AssetContainer.prototype.addAllToScene = function () {
  28860. var _this = this;
  28861. this.cameras.forEach(function (o) {
  28862. _this.scene.addCamera(o);
  28863. });
  28864. this.lights.forEach(function (o) {
  28865. _this.scene.addLight(o);
  28866. });
  28867. this.meshes.forEach(function (o) {
  28868. _this.scene.addMesh(o);
  28869. });
  28870. this.skeletons.forEach(function (o) {
  28871. _this.scene.addSkeleton(o);
  28872. });
  28873. this.animations.forEach(function (o) {
  28874. _this.scene.addAnimation(o);
  28875. });
  28876. this.animationGroups.forEach(function (o) {
  28877. _this.scene.addAnimationGroup(o);
  28878. });
  28879. this.multiMaterials.forEach(function (o) {
  28880. _this.scene.addMultiMaterial(o);
  28881. });
  28882. this.materials.forEach(function (o) {
  28883. _this.scene.addMaterial(o);
  28884. });
  28885. this.morphTargetManagers.forEach(function (o) {
  28886. _this.scene.addMorphTargetManager(o);
  28887. });
  28888. this.geometries.forEach(function (o) {
  28889. _this.scene.addGeometry(o);
  28890. });
  28891. this.transformNodes.forEach(function (o) {
  28892. _this.scene.addTransformNode(o);
  28893. });
  28894. this.actionManagers.forEach(function (o) {
  28895. _this.scene.addActionManager(o);
  28896. });
  28897. this.sounds.forEach(function (o) {
  28898. o.play();
  28899. o.autoplay = true;
  28900. _this.scene.mainSoundTrack.AddSound(o);
  28901. });
  28902. this.textures.forEach(function (o) {
  28903. _this.scene.addTexture(o);
  28904. });
  28905. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28906. var component = _a[_i];
  28907. component.addFromContainer(this.scene);
  28908. }
  28909. };
  28910. /**
  28911. * Removes all the assets in the container from the scene
  28912. */
  28913. AssetContainer.prototype.removeAllFromScene = function () {
  28914. var _this = this;
  28915. this.cameras.forEach(function (o) {
  28916. _this.scene.removeCamera(o);
  28917. });
  28918. this.lights.forEach(function (o) {
  28919. _this.scene.removeLight(o);
  28920. });
  28921. this.meshes.forEach(function (o) {
  28922. _this.scene.removeMesh(o);
  28923. });
  28924. this.skeletons.forEach(function (o) {
  28925. _this.scene.removeSkeleton(o);
  28926. });
  28927. this.animations.forEach(function (o) {
  28928. _this.scene.removeAnimation(o);
  28929. });
  28930. this.animationGroups.forEach(function (o) {
  28931. _this.scene.removeAnimationGroup(o);
  28932. });
  28933. this.multiMaterials.forEach(function (o) {
  28934. _this.scene.removeMultiMaterial(o);
  28935. });
  28936. this.materials.forEach(function (o) {
  28937. _this.scene.removeMaterial(o);
  28938. });
  28939. this.morphTargetManagers.forEach(function (o) {
  28940. _this.scene.removeMorphTargetManager(o);
  28941. });
  28942. this.geometries.forEach(function (o) {
  28943. _this.scene.removeGeometry(o);
  28944. });
  28945. this.transformNodes.forEach(function (o) {
  28946. _this.scene.removeTransformNode(o);
  28947. });
  28948. this.actionManagers.forEach(function (o) {
  28949. _this.scene.removeActionManager(o);
  28950. });
  28951. this.sounds.forEach(function (o) {
  28952. o.stop();
  28953. o.autoplay = false;
  28954. _this.scene.mainSoundTrack.RemoveSound(o);
  28955. });
  28956. this.textures.forEach(function (o) {
  28957. _this.scene.removeTexture(o);
  28958. });
  28959. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28960. var component = _a[_i];
  28961. component.removeFromContainer(this.scene);
  28962. }
  28963. };
  28964. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28965. if (!sourceAssets) {
  28966. return;
  28967. }
  28968. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28969. var asset = sourceAssets_1[_i];
  28970. var move = true;
  28971. if (keepAssets) {
  28972. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28973. var keepAsset = keepAssets_1[_a];
  28974. if (asset === keepAsset) {
  28975. move = false;
  28976. break;
  28977. }
  28978. }
  28979. }
  28980. if (move) {
  28981. targetAssets.push(asset);
  28982. }
  28983. }
  28984. };
  28985. /**
  28986. * Removes all the assets contained in the scene and adds them to the container.
  28987. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28988. */
  28989. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28990. if (keepAssets === undefined) {
  28991. keepAssets = new KeepAssets();
  28992. }
  28993. for (var key in this) {
  28994. if (this.hasOwnProperty(key)) {
  28995. this[key] = this[key] || [];
  28996. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28997. }
  28998. }
  28999. this.removeAllFromScene();
  29000. };
  29001. /**
  29002. * 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.
  29003. * @returns the root mesh
  29004. */
  29005. AssetContainer.prototype.createRootMesh = function () {
  29006. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29007. this.meshes.forEach(function (m) {
  29008. if (!m.parent) {
  29009. rootMesh.addChild(m);
  29010. }
  29011. });
  29012. this.meshes.unshift(rootMesh);
  29013. return rootMesh;
  29014. };
  29015. return AssetContainer;
  29016. }(BABYLON.AbstractScene));
  29017. BABYLON.AssetContainer = AssetContainer;
  29018. })(BABYLON || (BABYLON = {}));
  29019. //# sourceMappingURL=babylon.assetContainer.js.map
  29020. var BABYLON;
  29021. (function (BABYLON) {
  29022. var Buffer = /** @class */ (function () {
  29023. /**
  29024. * Constructor
  29025. * @param engine the engine
  29026. * @param data the data to use for this buffer
  29027. * @param updatable whether the data is updatable
  29028. * @param stride the stride (optional)
  29029. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29030. * @param instanced whether the buffer is instanced (optional)
  29031. * @param useBytes set to true if the stride in in bytes (optional)
  29032. */
  29033. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29034. if (stride === void 0) { stride = 0; }
  29035. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29036. if (instanced === void 0) { instanced = false; }
  29037. if (useBytes === void 0) { useBytes = false; }
  29038. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29039. this._engine = engine.getScene().getEngine();
  29040. }
  29041. else {
  29042. this._engine = engine;
  29043. }
  29044. this._updatable = updatable;
  29045. this._instanced = instanced;
  29046. this._data = data;
  29047. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29048. if (!postponeInternalCreation) { // by default
  29049. this.create();
  29050. }
  29051. }
  29052. /**
  29053. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29054. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29055. * @param offset defines offset in the buffer (0 by default)
  29056. * @param size defines the size in floats of attributes (position is 3 for instance)
  29057. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29058. * @param instanced defines if the vertex buffer contains indexed data
  29059. * @param useBytes defines if the offset and stride are in bytes
  29060. * @returns the new vertex buffer
  29061. */
  29062. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29063. if (useBytes === void 0) { useBytes = false; }
  29064. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29065. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29066. // a lot of these parameters are ignored as they are overriden by the buffer
  29067. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29068. };
  29069. // Properties
  29070. Buffer.prototype.isUpdatable = function () {
  29071. return this._updatable;
  29072. };
  29073. Buffer.prototype.getData = function () {
  29074. return this._data;
  29075. };
  29076. Buffer.prototype.getBuffer = function () {
  29077. return this._buffer;
  29078. };
  29079. /**
  29080. * Gets the stride in float32 units (i.e. byte stride / 4).
  29081. * May not be an integer if the byte stride is not divisible by 4.
  29082. * DEPRECATED. Use byteStride instead.
  29083. * @returns the stride in float32 units
  29084. */
  29085. Buffer.prototype.getStrideSize = function () {
  29086. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29087. };
  29088. // Methods
  29089. Buffer.prototype.create = function (data) {
  29090. if (data === void 0) { data = null; }
  29091. if (!data && this._buffer) {
  29092. return; // nothing to do
  29093. }
  29094. data = data || this._data;
  29095. if (!data) {
  29096. return;
  29097. }
  29098. if (!this._buffer) { // create buffer
  29099. if (this._updatable) {
  29100. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29101. this._data = data;
  29102. }
  29103. else {
  29104. this._buffer = this._engine.createVertexBuffer(data);
  29105. }
  29106. }
  29107. else if (this._updatable) { // update buffer
  29108. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29109. this._data = data;
  29110. }
  29111. };
  29112. Buffer.prototype._rebuild = function () {
  29113. this._buffer = null;
  29114. this.create(this._data);
  29115. };
  29116. Buffer.prototype.update = function (data) {
  29117. this.create(data);
  29118. };
  29119. /**
  29120. * Updates the data directly.
  29121. * @param data the new data
  29122. * @param offset the new offset
  29123. * @param vertexCount the vertex count (optional)
  29124. * @param useBytes set to true if the offset is in bytes
  29125. */
  29126. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29127. if (useBytes === void 0) { useBytes = false; }
  29128. if (!this._buffer) {
  29129. return;
  29130. }
  29131. if (this._updatable) { // update buffer
  29132. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29133. this._data = null;
  29134. }
  29135. };
  29136. Buffer.prototype.dispose = function () {
  29137. if (!this._buffer) {
  29138. return;
  29139. }
  29140. if (this._engine._releaseBuffer(this._buffer)) {
  29141. this._buffer = null;
  29142. }
  29143. };
  29144. return Buffer;
  29145. }());
  29146. BABYLON.Buffer = Buffer;
  29147. })(BABYLON || (BABYLON = {}));
  29148. //# sourceMappingURL=babylon.buffer.js.map
  29149. var BABYLON;
  29150. (function (BABYLON) {
  29151. var VertexBuffer = /** @class */ (function () {
  29152. /**
  29153. * Constructor
  29154. * @param engine the engine
  29155. * @param data the data to use for this vertex buffer
  29156. * @param kind the vertex buffer kind
  29157. * @param updatable whether the data is updatable
  29158. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29159. * @param stride the stride (optional)
  29160. * @param instanced whether the buffer is instanced (optional)
  29161. * @param offset the offset of the data (optional)
  29162. * @param size the number of components (optional)
  29163. * @param type the type of the component (optional)
  29164. * @param normalized whether the data contains normalized data (optional)
  29165. * @param useBytes set to true if stride and offset are in bytes (optional)
  29166. */
  29167. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29168. if (normalized === void 0) { normalized = false; }
  29169. if (useBytes === void 0) { useBytes = false; }
  29170. if (data instanceof BABYLON.Buffer) {
  29171. this._buffer = data;
  29172. this._ownsBuffer = false;
  29173. }
  29174. else {
  29175. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29176. this._ownsBuffer = true;
  29177. }
  29178. this._kind = kind;
  29179. if (type == undefined) {
  29180. var data_1 = this.getData();
  29181. this.type = VertexBuffer.FLOAT;
  29182. if (data_1 instanceof Int8Array)
  29183. this.type = VertexBuffer.BYTE;
  29184. else if (data_1 instanceof Uint8Array)
  29185. this.type = VertexBuffer.UNSIGNED_BYTE;
  29186. else if (data_1 instanceof Int16Array)
  29187. this.type = VertexBuffer.SHORT;
  29188. else if (data_1 instanceof Uint16Array)
  29189. this.type = VertexBuffer.UNSIGNED_SHORT;
  29190. else if (data_1 instanceof Int32Array)
  29191. this.type = VertexBuffer.INT;
  29192. else if (data_1 instanceof Uint32Array)
  29193. this.type = VertexBuffer.UNSIGNED_INT;
  29194. }
  29195. else {
  29196. this.type = type;
  29197. }
  29198. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29199. if (useBytes) {
  29200. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29201. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29202. this.byteOffset = offset || 0;
  29203. }
  29204. else {
  29205. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29206. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29207. this.byteOffset = (offset || 0) * typeByteLength;
  29208. }
  29209. this.normalized = normalized;
  29210. this._instanced = instanced !== undefined ? instanced : false;
  29211. this._instanceDivisor = instanced ? 1 : 0;
  29212. }
  29213. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29214. /**
  29215. * Gets or sets the instance divisor when in instanced mode
  29216. */
  29217. get: function () {
  29218. return this._instanceDivisor;
  29219. },
  29220. set: function (value) {
  29221. this._instanceDivisor = value;
  29222. if (value == 0) {
  29223. this._instanced = false;
  29224. }
  29225. else {
  29226. this._instanced = true;
  29227. }
  29228. },
  29229. enumerable: true,
  29230. configurable: true
  29231. });
  29232. VertexBuffer.prototype._rebuild = function () {
  29233. if (!this._buffer) {
  29234. return;
  29235. }
  29236. this._buffer._rebuild();
  29237. };
  29238. /**
  29239. * Returns the kind of the VertexBuffer (string).
  29240. */
  29241. VertexBuffer.prototype.getKind = function () {
  29242. return this._kind;
  29243. };
  29244. // Properties
  29245. /**
  29246. * Boolean : is the VertexBuffer updatable ?
  29247. */
  29248. VertexBuffer.prototype.isUpdatable = function () {
  29249. return this._buffer.isUpdatable();
  29250. };
  29251. /**
  29252. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29253. */
  29254. VertexBuffer.prototype.getData = function () {
  29255. return this._buffer.getData();
  29256. };
  29257. /**
  29258. * Returns the WebGLBuffer associated to the VertexBuffer.
  29259. */
  29260. VertexBuffer.prototype.getBuffer = function () {
  29261. return this._buffer.getBuffer();
  29262. };
  29263. /**
  29264. * Returns the stride as a multiple of the type byte length.
  29265. * DEPRECATED. Use byteStride instead.
  29266. */
  29267. VertexBuffer.prototype.getStrideSize = function () {
  29268. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29269. };
  29270. /**
  29271. * Returns the offset as a multiple of the type byte length.
  29272. * DEPRECATED. Use byteOffset instead.
  29273. */
  29274. VertexBuffer.prototype.getOffset = function () {
  29275. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29276. };
  29277. /**
  29278. * Returns the number of components per vertex attribute (integer).
  29279. */
  29280. VertexBuffer.prototype.getSize = function () {
  29281. return this._size;
  29282. };
  29283. /**
  29284. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29285. */
  29286. VertexBuffer.prototype.getIsInstanced = function () {
  29287. return this._instanced;
  29288. };
  29289. /**
  29290. * Returns the instancing divisor, zero for non-instanced (integer).
  29291. */
  29292. VertexBuffer.prototype.getInstanceDivisor = function () {
  29293. return this._instanceDivisor;
  29294. };
  29295. // Methods
  29296. /**
  29297. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29298. * Returns the created WebGLBuffer.
  29299. */
  29300. VertexBuffer.prototype.create = function (data) {
  29301. return this._buffer.create(data);
  29302. };
  29303. /**
  29304. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29305. * This function will create a new buffer if the current one is not updatable
  29306. * Returns the updated WebGLBuffer.
  29307. */
  29308. VertexBuffer.prototype.update = function (data) {
  29309. return this._buffer.update(data);
  29310. };
  29311. /**
  29312. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29313. * Returns the directly updated WebGLBuffer.
  29314. * @param data the new data
  29315. * @param offset the new offset
  29316. * @param useBytes set to true if the offset is in bytes
  29317. */
  29318. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29319. if (useBytes === void 0) { useBytes = false; }
  29320. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29321. };
  29322. /**
  29323. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29324. */
  29325. VertexBuffer.prototype.dispose = function () {
  29326. if (this._ownsBuffer) {
  29327. this._buffer.dispose();
  29328. }
  29329. };
  29330. /**
  29331. * Enumerates each value of this vertex buffer as numbers.
  29332. * @param count the number of values to enumerate
  29333. * @param callback the callback function called for each value
  29334. */
  29335. VertexBuffer.prototype.forEach = function (count, callback) {
  29336. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29337. };
  29338. Object.defineProperty(VertexBuffer, "PositionKind", {
  29339. get: function () {
  29340. return VertexBuffer._PositionKind;
  29341. },
  29342. enumerable: true,
  29343. configurable: true
  29344. });
  29345. Object.defineProperty(VertexBuffer, "NormalKind", {
  29346. get: function () {
  29347. return VertexBuffer._NormalKind;
  29348. },
  29349. enumerable: true,
  29350. configurable: true
  29351. });
  29352. Object.defineProperty(VertexBuffer, "TangentKind", {
  29353. get: function () {
  29354. return VertexBuffer._TangentKind;
  29355. },
  29356. enumerable: true,
  29357. configurable: true
  29358. });
  29359. Object.defineProperty(VertexBuffer, "UVKind", {
  29360. get: function () {
  29361. return VertexBuffer._UVKind;
  29362. },
  29363. enumerable: true,
  29364. configurable: true
  29365. });
  29366. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29367. get: function () {
  29368. return VertexBuffer._UV2Kind;
  29369. },
  29370. enumerable: true,
  29371. configurable: true
  29372. });
  29373. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29374. get: function () {
  29375. return VertexBuffer._UV3Kind;
  29376. },
  29377. enumerable: true,
  29378. configurable: true
  29379. });
  29380. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29381. get: function () {
  29382. return VertexBuffer._UV4Kind;
  29383. },
  29384. enumerable: true,
  29385. configurable: true
  29386. });
  29387. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29388. get: function () {
  29389. return VertexBuffer._UV5Kind;
  29390. },
  29391. enumerable: true,
  29392. configurable: true
  29393. });
  29394. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29395. get: function () {
  29396. return VertexBuffer._UV6Kind;
  29397. },
  29398. enumerable: true,
  29399. configurable: true
  29400. });
  29401. Object.defineProperty(VertexBuffer, "ColorKind", {
  29402. get: function () {
  29403. return VertexBuffer._ColorKind;
  29404. },
  29405. enumerable: true,
  29406. configurable: true
  29407. });
  29408. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29409. get: function () {
  29410. return VertexBuffer._MatricesIndicesKind;
  29411. },
  29412. enumerable: true,
  29413. configurable: true
  29414. });
  29415. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29416. get: function () {
  29417. return VertexBuffer._MatricesWeightsKind;
  29418. },
  29419. enumerable: true,
  29420. configurable: true
  29421. });
  29422. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29423. get: function () {
  29424. return VertexBuffer._MatricesIndicesExtraKind;
  29425. },
  29426. enumerable: true,
  29427. configurable: true
  29428. });
  29429. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29430. get: function () {
  29431. return VertexBuffer._MatricesWeightsExtraKind;
  29432. },
  29433. enumerable: true,
  29434. configurable: true
  29435. });
  29436. /**
  29437. * Deduces the stride given a kind.
  29438. * @param kind The kind string to deduce
  29439. * @returns The deduced stride
  29440. */
  29441. VertexBuffer.DeduceStride = function (kind) {
  29442. switch (kind) {
  29443. case VertexBuffer.UVKind:
  29444. case VertexBuffer.UV2Kind:
  29445. case VertexBuffer.UV3Kind:
  29446. case VertexBuffer.UV4Kind:
  29447. case VertexBuffer.UV5Kind:
  29448. case VertexBuffer.UV6Kind:
  29449. return 2;
  29450. case VertexBuffer.NormalKind:
  29451. case VertexBuffer.PositionKind:
  29452. return 3;
  29453. case VertexBuffer.ColorKind:
  29454. case VertexBuffer.MatricesIndicesKind:
  29455. case VertexBuffer.MatricesIndicesExtraKind:
  29456. case VertexBuffer.MatricesWeightsKind:
  29457. case VertexBuffer.MatricesWeightsExtraKind:
  29458. case VertexBuffer.TangentKind:
  29459. return 4;
  29460. default:
  29461. throw new Error("Invalid kind '" + kind + "'");
  29462. }
  29463. };
  29464. /**
  29465. * Gets the byte length of the given type.
  29466. * @param type the type
  29467. * @returns the number of bytes
  29468. */
  29469. VertexBuffer.GetTypeByteLength = function (type) {
  29470. switch (type) {
  29471. case VertexBuffer.BYTE:
  29472. case VertexBuffer.UNSIGNED_BYTE:
  29473. return 1;
  29474. case VertexBuffer.SHORT:
  29475. case VertexBuffer.UNSIGNED_SHORT:
  29476. return 2;
  29477. case VertexBuffer.INT:
  29478. case VertexBuffer.FLOAT:
  29479. return 4;
  29480. default:
  29481. throw new Error("Invalid type '" + type + "'");
  29482. }
  29483. };
  29484. /**
  29485. * Enumerates each value of the given parameters as numbers.
  29486. * @param data the data to enumerate
  29487. * @param byteOffset the byte offset of the data
  29488. * @param byteStride the byte stride of the data
  29489. * @param componentCount the number of components per element
  29490. * @param componentType the type of the component
  29491. * @param count the total number of components
  29492. * @param normalized whether the data is normalized
  29493. * @param callback the callback function called for each value
  29494. */
  29495. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29496. if (data instanceof Array) {
  29497. var offset = byteOffset / 4;
  29498. var stride = byteStride / 4;
  29499. for (var index = 0; index < count; index += componentCount) {
  29500. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29501. callback(data[offset + componentIndex], index + componentIndex);
  29502. }
  29503. offset += stride;
  29504. }
  29505. }
  29506. else {
  29507. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29508. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29509. for (var index = 0; index < count; index += componentCount) {
  29510. var componentByteOffset = byteOffset;
  29511. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29512. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29513. callback(value, index + componentIndex);
  29514. componentByteOffset += componentByteLength;
  29515. }
  29516. byteOffset += byteStride;
  29517. }
  29518. }
  29519. };
  29520. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29521. switch (type) {
  29522. case VertexBuffer.BYTE: {
  29523. var value = dataView.getInt8(byteOffset);
  29524. if (normalized) {
  29525. value = Math.max(value / 127, -1);
  29526. }
  29527. return value;
  29528. }
  29529. case VertexBuffer.UNSIGNED_BYTE: {
  29530. var value = dataView.getUint8(byteOffset);
  29531. if (normalized) {
  29532. value = value / 255;
  29533. }
  29534. return value;
  29535. }
  29536. case VertexBuffer.SHORT: {
  29537. var value = dataView.getInt16(byteOffset, true);
  29538. if (normalized) {
  29539. value = Math.max(value / 16383, -1);
  29540. }
  29541. return value;
  29542. }
  29543. case VertexBuffer.UNSIGNED_SHORT: {
  29544. var value = dataView.getUint16(byteOffset, true);
  29545. if (normalized) {
  29546. value = value / 65535;
  29547. }
  29548. return value;
  29549. }
  29550. case VertexBuffer.FLOAT: {
  29551. return dataView.getFloat32(byteOffset, true);
  29552. }
  29553. default: {
  29554. throw new Error("Invalid component type " + type);
  29555. }
  29556. }
  29557. };
  29558. /**
  29559. * The byte type.
  29560. */
  29561. VertexBuffer.BYTE = 5120;
  29562. /**
  29563. * The unsigned byte type.
  29564. */
  29565. VertexBuffer.UNSIGNED_BYTE = 5121;
  29566. /**
  29567. * The short type.
  29568. */
  29569. VertexBuffer.SHORT = 5122;
  29570. /**
  29571. * The unsigned short type.
  29572. */
  29573. VertexBuffer.UNSIGNED_SHORT = 5123;
  29574. /**
  29575. * The integer type.
  29576. */
  29577. VertexBuffer.INT = 5124;
  29578. /**
  29579. * The unsigned integer type.
  29580. */
  29581. VertexBuffer.UNSIGNED_INT = 5125;
  29582. /**
  29583. * The float type.
  29584. */
  29585. VertexBuffer.FLOAT = 5126;
  29586. // Enums
  29587. VertexBuffer._PositionKind = "position";
  29588. VertexBuffer._NormalKind = "normal";
  29589. VertexBuffer._TangentKind = "tangent";
  29590. VertexBuffer._UVKind = "uv";
  29591. VertexBuffer._UV2Kind = "uv2";
  29592. VertexBuffer._UV3Kind = "uv3";
  29593. VertexBuffer._UV4Kind = "uv4";
  29594. VertexBuffer._UV5Kind = "uv5";
  29595. VertexBuffer._UV6Kind = "uv6";
  29596. VertexBuffer._ColorKind = "color";
  29597. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29598. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29599. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29600. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29601. return VertexBuffer;
  29602. }());
  29603. BABYLON.VertexBuffer = VertexBuffer;
  29604. })(BABYLON || (BABYLON = {}));
  29605. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29606. var BABYLON;
  29607. (function (BABYLON) {
  29608. /**
  29609. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29610. */
  29611. var DummyInternalTextureTracker = /** @class */ (function () {
  29612. function DummyInternalTextureTracker() {
  29613. /**
  29614. * Gets or set the previous tracker in the list
  29615. */
  29616. this.previous = null;
  29617. /**
  29618. * Gets or set the next tracker in the list
  29619. */
  29620. this.next = null;
  29621. }
  29622. return DummyInternalTextureTracker;
  29623. }());
  29624. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29625. })(BABYLON || (BABYLON = {}));
  29626. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29627. var BABYLON;
  29628. (function (BABYLON) {
  29629. /**
  29630. * Class used to store data associated with WebGL texture data for the engine
  29631. * This class should not be used directly
  29632. */
  29633. var InternalTexture = /** @class */ (function () {
  29634. /**
  29635. * Creates a new InternalTexture
  29636. * @param engine defines the engine to use
  29637. * @param dataSource defines the type of data that will be used
  29638. */
  29639. function InternalTexture(engine, dataSource) {
  29640. /**
  29641. * Observable called when the texture is loaded
  29642. */
  29643. this.onLoadedObservable = new BABYLON.Observable();
  29644. /**
  29645. * Gets or set the previous tracker in the list
  29646. */
  29647. this.previous = null;
  29648. /**
  29649. * Gets or set the next tracker in the list
  29650. */
  29651. this.next = null;
  29652. // Private
  29653. /** @hidden */
  29654. this._initialSlot = -1;
  29655. /** @hidden */
  29656. this._designatedSlot = -1;
  29657. /** @hidden */
  29658. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29659. /** @hidden */
  29660. this._comparisonFunction = 0;
  29661. /** @hidden */
  29662. this._sphericalPolynomial = null;
  29663. /** @hidden */
  29664. this._lodGenerationScale = 0;
  29665. /** @hidden */
  29666. this._lodGenerationOffset = 0;
  29667. /** @hidden */
  29668. this._isRGBD = false;
  29669. /** @hidden */
  29670. this._references = 1;
  29671. this._engine = engine;
  29672. this._dataSource = dataSource;
  29673. this._webGLTexture = engine._createTexture();
  29674. }
  29675. /**
  29676. * Gets the Engine the texture belongs to.
  29677. * @returns The babylon engine
  29678. */
  29679. InternalTexture.prototype.getEngine = function () {
  29680. return this._engine;
  29681. };
  29682. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29683. /**
  29684. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29685. */
  29686. get: function () {
  29687. return this._dataSource;
  29688. },
  29689. enumerable: true,
  29690. configurable: true
  29691. });
  29692. /**
  29693. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29694. */
  29695. InternalTexture.prototype.incrementReferences = function () {
  29696. this._references++;
  29697. };
  29698. /**
  29699. * Change the size of the texture (not the size of the content)
  29700. * @param width defines the new width
  29701. * @param height defines the new height
  29702. * @param depth defines the new depth (1 by default)
  29703. */
  29704. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29705. if (depth === void 0) { depth = 1; }
  29706. this.width = width;
  29707. this.height = height;
  29708. this.depth = depth;
  29709. this.baseWidth = width;
  29710. this.baseHeight = height;
  29711. this.baseDepth = depth;
  29712. this._size = width * height * depth;
  29713. };
  29714. /** @hidden */
  29715. InternalTexture.prototype._rebuild = function () {
  29716. var _this = this;
  29717. var proxy;
  29718. this.isReady = false;
  29719. this._cachedCoordinatesMode = null;
  29720. this._cachedWrapU = null;
  29721. this._cachedWrapV = null;
  29722. this._cachedAnisotropicFilteringLevel = null;
  29723. switch (this._dataSource) {
  29724. case InternalTexture.DATASOURCE_TEMP:
  29725. return;
  29726. case InternalTexture.DATASOURCE_URL:
  29727. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29728. _this.isReady = true;
  29729. }, null, this._buffer, undefined, this.format);
  29730. proxy._swapAndDie(this);
  29731. return;
  29732. case InternalTexture.DATASOURCE_RAW:
  29733. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29734. proxy._swapAndDie(this);
  29735. this.isReady = true;
  29736. return;
  29737. case InternalTexture.DATASOURCE_RAW3D:
  29738. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29739. proxy._swapAndDie(this);
  29740. this.isReady = true;
  29741. return;
  29742. case InternalTexture.DATASOURCE_DYNAMIC:
  29743. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29744. proxy._swapAndDie(this);
  29745. // The engine will make sure to update content so no need to flag it as isReady = true
  29746. return;
  29747. case InternalTexture.DATASOURCE_RENDERTARGET:
  29748. var options = new BABYLON.RenderTargetCreationOptions();
  29749. options.generateDepthBuffer = this._generateDepthBuffer;
  29750. options.generateMipMaps = this.generateMipMaps;
  29751. options.generateStencilBuffer = this._generateStencilBuffer;
  29752. options.samplingMode = this.samplingMode;
  29753. options.type = this.type;
  29754. if (this.isCube) {
  29755. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29756. }
  29757. else {
  29758. var size = {
  29759. width: this.width,
  29760. height: this.height
  29761. };
  29762. proxy = this._engine.createRenderTargetTexture(size, options);
  29763. }
  29764. proxy._swapAndDie(this);
  29765. this.isReady = true;
  29766. return;
  29767. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29768. var depthTextureOptions = {
  29769. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29770. comparisonFunction: this._comparisonFunction,
  29771. generateStencil: this._generateStencilBuffer,
  29772. isCube: this.isCube
  29773. };
  29774. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29775. proxy._swapAndDie(this);
  29776. this.isReady = true;
  29777. return;
  29778. case InternalTexture.DATASOURCE_CUBE:
  29779. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29780. _this.isReady = true;
  29781. }, null, this.format, this._extension);
  29782. proxy._swapAndDie(this);
  29783. return;
  29784. case InternalTexture.DATASOURCE_CUBERAW:
  29785. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29786. proxy._swapAndDie(this);
  29787. this.isReady = true;
  29788. return;
  29789. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29790. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29791. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29792. _this.isReady = true;
  29793. });
  29794. proxy._swapAndDie(this);
  29795. return;
  29796. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29797. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29798. if (proxy) {
  29799. proxy._swapAndDie(_this);
  29800. }
  29801. _this.isReady = true;
  29802. }, null, this.format, this._extension);
  29803. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29804. return;
  29805. }
  29806. };
  29807. InternalTexture.prototype._swapAndDie = function (target) {
  29808. target._webGLTexture = this._webGLTexture;
  29809. if (this._framebuffer) {
  29810. target._framebuffer = this._framebuffer;
  29811. }
  29812. if (this._depthStencilBuffer) {
  29813. target._depthStencilBuffer = this._depthStencilBuffer;
  29814. }
  29815. if (this._lodTextureHigh) {
  29816. if (target._lodTextureHigh) {
  29817. target._lodTextureHigh.dispose();
  29818. }
  29819. target._lodTextureHigh = this._lodTextureHigh;
  29820. }
  29821. if (this._lodTextureMid) {
  29822. if (target._lodTextureMid) {
  29823. target._lodTextureMid.dispose();
  29824. }
  29825. target._lodTextureMid = this._lodTextureMid;
  29826. }
  29827. if (this._lodTextureLow) {
  29828. if (target._lodTextureLow) {
  29829. target._lodTextureLow.dispose();
  29830. }
  29831. target._lodTextureLow = this._lodTextureLow;
  29832. }
  29833. var cache = this._engine.getLoadedTexturesCache();
  29834. var index = cache.indexOf(this);
  29835. if (index !== -1) {
  29836. cache.splice(index, 1);
  29837. }
  29838. };
  29839. /**
  29840. * Dispose the current allocated resources
  29841. */
  29842. InternalTexture.prototype.dispose = function () {
  29843. if (!this._webGLTexture) {
  29844. return;
  29845. }
  29846. this._references--;
  29847. if (this._references === 0) {
  29848. this._engine._releaseTexture(this);
  29849. this._webGLTexture = null;
  29850. this.previous = null;
  29851. this.next = null;
  29852. }
  29853. };
  29854. /**
  29855. * The source of the texture data is unknown
  29856. */
  29857. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29858. /**
  29859. * Texture data comes from an URL
  29860. */
  29861. InternalTexture.DATASOURCE_URL = 1;
  29862. /**
  29863. * Texture data is only used for temporary storage
  29864. */
  29865. InternalTexture.DATASOURCE_TEMP = 2;
  29866. /**
  29867. * Texture data comes from raw data (ArrayBuffer)
  29868. */
  29869. InternalTexture.DATASOURCE_RAW = 3;
  29870. /**
  29871. * Texture content is dynamic (video or dynamic texture)
  29872. */
  29873. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29874. /**
  29875. * Texture content is generated by rendering to it
  29876. */
  29877. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29878. /**
  29879. * Texture content is part of a multi render target process
  29880. */
  29881. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29882. /**
  29883. * Texture data comes from a cube data file
  29884. */
  29885. InternalTexture.DATASOURCE_CUBE = 7;
  29886. /**
  29887. * Texture data comes from a raw cube data
  29888. */
  29889. InternalTexture.DATASOURCE_CUBERAW = 8;
  29890. /**
  29891. * Texture data come from a prefiltered cube data file
  29892. */
  29893. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29894. /**
  29895. * Texture content is raw 3D data
  29896. */
  29897. InternalTexture.DATASOURCE_RAW3D = 10;
  29898. /**
  29899. * Texture content is a depth texture
  29900. */
  29901. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29902. /**
  29903. * Texture data comes from a raw cube data encoded with RGBD
  29904. */
  29905. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29906. return InternalTexture;
  29907. }());
  29908. BABYLON.InternalTexture = InternalTexture;
  29909. })(BABYLON || (BABYLON = {}));
  29910. //# sourceMappingURL=babylon.internalTexture.js.map
  29911. var BABYLON;
  29912. (function (BABYLON) {
  29913. var BaseTexture = /** @class */ (function () {
  29914. function BaseTexture(scene) {
  29915. this._hasAlpha = false;
  29916. this.getAlphaFromRGB = false;
  29917. this.level = 1;
  29918. this.coordinatesIndex = 0;
  29919. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29920. /**
  29921. * | Value | Type | Description |
  29922. * | ----- | ------------------ | ----------- |
  29923. * | 0 | CLAMP_ADDRESSMODE | |
  29924. * | 1 | WRAP_ADDRESSMODE | |
  29925. * | 2 | MIRROR_ADDRESSMODE | |
  29926. */
  29927. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29928. /**
  29929. * | Value | Type | Description |
  29930. * | ----- | ------------------ | ----------- |
  29931. * | 0 | CLAMP_ADDRESSMODE | |
  29932. * | 1 | WRAP_ADDRESSMODE | |
  29933. * | 2 | MIRROR_ADDRESSMODE | |
  29934. */
  29935. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29936. /**
  29937. * | Value | Type | Description |
  29938. * | ----- | ------------------ | ----------- |
  29939. * | 0 | CLAMP_ADDRESSMODE | |
  29940. * | 1 | WRAP_ADDRESSMODE | |
  29941. * | 2 | MIRROR_ADDRESSMODE | |
  29942. */
  29943. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29944. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29945. this.isCube = false;
  29946. this.is3D = false;
  29947. this.gammaSpace = true;
  29948. this.invertZ = false;
  29949. this.lodLevelInAlpha = false;
  29950. this.isRenderTarget = false;
  29951. this.animations = new Array();
  29952. /**
  29953. * An event triggered when the texture is disposed.
  29954. */
  29955. this.onDisposeObservable = new BABYLON.Observable();
  29956. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29957. this._cachedSize = BABYLON.Size.Zero();
  29958. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29959. if (this._scene) {
  29960. this._scene.textures.push(this);
  29961. }
  29962. this._uid = null;
  29963. }
  29964. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29965. get: function () {
  29966. return this._hasAlpha;
  29967. },
  29968. set: function (value) {
  29969. if (this._hasAlpha === value) {
  29970. return;
  29971. }
  29972. this._hasAlpha = value;
  29973. if (this._scene) {
  29974. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29975. }
  29976. },
  29977. enumerable: true,
  29978. configurable: true
  29979. });
  29980. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29981. get: function () {
  29982. return this._coordinatesMode;
  29983. },
  29984. /**
  29985. * How a texture is mapped.
  29986. *
  29987. * | Value | Type | Description |
  29988. * | ----- | ----------------------------------- | ----------- |
  29989. * | 0 | EXPLICIT_MODE | |
  29990. * | 1 | SPHERICAL_MODE | |
  29991. * | 2 | PLANAR_MODE | |
  29992. * | 3 | CUBIC_MODE | |
  29993. * | 4 | PROJECTION_MODE | |
  29994. * | 5 | SKYBOX_MODE | |
  29995. * | 6 | INVCUBIC_MODE | |
  29996. * | 7 | EQUIRECTANGULAR_MODE | |
  29997. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29998. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29999. */
  30000. set: function (value) {
  30001. if (this._coordinatesMode === value) {
  30002. return;
  30003. }
  30004. this._coordinatesMode = value;
  30005. if (this._scene) {
  30006. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30007. }
  30008. },
  30009. enumerable: true,
  30010. configurable: true
  30011. });
  30012. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30013. /**
  30014. * Gets whether or not the texture contains RGBD data.
  30015. */
  30016. get: function () {
  30017. return this._texture != null && this._texture._isRGBD;
  30018. },
  30019. enumerable: true,
  30020. configurable: true
  30021. });
  30022. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30023. get: function () {
  30024. if (this._texture)
  30025. return this._texture._lodGenerationOffset;
  30026. return 0.0;
  30027. },
  30028. set: function (value) {
  30029. if (this._texture)
  30030. this._texture._lodGenerationOffset = value;
  30031. },
  30032. enumerable: true,
  30033. configurable: true
  30034. });
  30035. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30036. get: function () {
  30037. if (this._texture)
  30038. return this._texture._lodGenerationScale;
  30039. return 0.0;
  30040. },
  30041. set: function (value) {
  30042. if (this._texture)
  30043. this._texture._lodGenerationScale = value;
  30044. },
  30045. enumerable: true,
  30046. configurable: true
  30047. });
  30048. Object.defineProperty(BaseTexture.prototype, "uid", {
  30049. get: function () {
  30050. if (!this._uid) {
  30051. this._uid = BABYLON.Tools.RandomId();
  30052. }
  30053. return this._uid;
  30054. },
  30055. enumerable: true,
  30056. configurable: true
  30057. });
  30058. BaseTexture.prototype.toString = function () {
  30059. return this.name;
  30060. };
  30061. BaseTexture.prototype.getClassName = function () {
  30062. return "BaseTexture";
  30063. };
  30064. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30065. set: function (callback) {
  30066. if (this._onDisposeObserver) {
  30067. this.onDisposeObservable.remove(this._onDisposeObserver);
  30068. }
  30069. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30070. },
  30071. enumerable: true,
  30072. configurable: true
  30073. });
  30074. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30075. get: function () {
  30076. return true;
  30077. },
  30078. enumerable: true,
  30079. configurable: true
  30080. });
  30081. BaseTexture.prototype.getScene = function () {
  30082. return this._scene;
  30083. };
  30084. BaseTexture.prototype.getTextureMatrix = function () {
  30085. return BABYLON.Matrix.IdentityReadOnly;
  30086. };
  30087. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30088. return BABYLON.Matrix.IdentityReadOnly;
  30089. };
  30090. BaseTexture.prototype.getInternalTexture = function () {
  30091. return this._texture;
  30092. };
  30093. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30094. return !this.isBlocking || this.isReady();
  30095. };
  30096. BaseTexture.prototype.isReady = function () {
  30097. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30098. this.delayLoad();
  30099. return false;
  30100. }
  30101. if (this._texture) {
  30102. return this._texture.isReady;
  30103. }
  30104. return false;
  30105. };
  30106. BaseTexture.prototype.getSize = function () {
  30107. if (this._texture) {
  30108. if (this._texture.width) {
  30109. this._cachedSize.width = this._texture.width;
  30110. this._cachedSize.height = this._texture.height;
  30111. return this._cachedSize;
  30112. }
  30113. if (this._texture._size) {
  30114. this._cachedSize.width = this._texture._size;
  30115. this._cachedSize.height = this._texture._size;
  30116. return this._cachedSize;
  30117. }
  30118. }
  30119. return this._cachedSize;
  30120. };
  30121. BaseTexture.prototype.getBaseSize = function () {
  30122. if (!this.isReady() || !this._texture)
  30123. return BABYLON.Size.Zero();
  30124. if (this._texture._size) {
  30125. return new BABYLON.Size(this._texture._size, this._texture._size);
  30126. }
  30127. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30128. };
  30129. BaseTexture.prototype.scale = function (ratio) {
  30130. };
  30131. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30132. get: function () {
  30133. return false;
  30134. },
  30135. enumerable: true,
  30136. configurable: true
  30137. });
  30138. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30139. if (!this._scene) {
  30140. return null;
  30141. }
  30142. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30143. for (var index = 0; index < texturesCache.length; index++) {
  30144. var texturesCacheEntry = texturesCache[index];
  30145. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30146. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30147. texturesCacheEntry.incrementReferences();
  30148. return texturesCacheEntry;
  30149. }
  30150. }
  30151. }
  30152. return null;
  30153. };
  30154. BaseTexture.prototype._rebuild = function () {
  30155. };
  30156. BaseTexture.prototype.delayLoad = function () {
  30157. };
  30158. BaseTexture.prototype.clone = function () {
  30159. return null;
  30160. };
  30161. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30162. get: function () {
  30163. if (!this._texture) {
  30164. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30165. }
  30166. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30167. },
  30168. enumerable: true,
  30169. configurable: true
  30170. });
  30171. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30172. get: function () {
  30173. if (!this._texture) {
  30174. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30175. }
  30176. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30177. },
  30178. enumerable: true,
  30179. configurable: true
  30180. });
  30181. /**
  30182. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30183. * This will returns an RGBA array buffer containing either in values (0-255) or
  30184. * float values (0-1) depending of the underlying buffer type.
  30185. * @param faceIndex The face of the texture to read (in case of cube texture)
  30186. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30187. * @returns The Array buffer containing the pixels data.
  30188. */
  30189. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30190. if (faceIndex === void 0) { faceIndex = 0; }
  30191. if (level === void 0) { level = 0; }
  30192. if (!this._texture) {
  30193. return null;
  30194. }
  30195. var size = this.getSize();
  30196. var width = size.width;
  30197. var height = size.height;
  30198. var scene = this.getScene();
  30199. if (!scene) {
  30200. return null;
  30201. }
  30202. var engine = scene.getEngine();
  30203. if (level != 0) {
  30204. width = width / Math.pow(2, level);
  30205. height = height / Math.pow(2, level);
  30206. width = Math.round(width);
  30207. height = Math.round(height);
  30208. }
  30209. if (this._texture.isCube) {
  30210. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30211. }
  30212. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30213. };
  30214. BaseTexture.prototype.releaseInternalTexture = function () {
  30215. if (this._texture) {
  30216. this._texture.dispose();
  30217. this._texture = null;
  30218. }
  30219. };
  30220. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30221. get: function () {
  30222. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30223. return null;
  30224. }
  30225. if (!this._texture._sphericalPolynomial) {
  30226. this._texture._sphericalPolynomial =
  30227. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30228. }
  30229. return this._texture._sphericalPolynomial;
  30230. },
  30231. set: function (value) {
  30232. if (this._texture) {
  30233. this._texture._sphericalPolynomial = value;
  30234. }
  30235. },
  30236. enumerable: true,
  30237. configurable: true
  30238. });
  30239. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30240. get: function () {
  30241. if (this._texture) {
  30242. return this._texture._lodTextureHigh;
  30243. }
  30244. return null;
  30245. },
  30246. enumerable: true,
  30247. configurable: true
  30248. });
  30249. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30250. get: function () {
  30251. if (this._texture) {
  30252. return this._texture._lodTextureMid;
  30253. }
  30254. return null;
  30255. },
  30256. enumerable: true,
  30257. configurable: true
  30258. });
  30259. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30260. get: function () {
  30261. if (this._texture) {
  30262. return this._texture._lodTextureLow;
  30263. }
  30264. return null;
  30265. },
  30266. enumerable: true,
  30267. configurable: true
  30268. });
  30269. BaseTexture.prototype.dispose = function () {
  30270. if (!this._scene) {
  30271. return;
  30272. }
  30273. // Animations
  30274. this._scene.stopAnimation(this);
  30275. // Remove from scene
  30276. this._scene._removePendingData(this);
  30277. var index = this._scene.textures.indexOf(this);
  30278. if (index >= 0) {
  30279. this._scene.textures.splice(index, 1);
  30280. }
  30281. if (this._texture === undefined) {
  30282. return;
  30283. }
  30284. // Release
  30285. this.releaseInternalTexture();
  30286. // Callback
  30287. this.onDisposeObservable.notifyObservers(this);
  30288. this.onDisposeObservable.clear();
  30289. };
  30290. BaseTexture.prototype.serialize = function () {
  30291. if (!this.name) {
  30292. return null;
  30293. }
  30294. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30295. // Animations
  30296. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30297. return serializationObject;
  30298. };
  30299. BaseTexture.WhenAllReady = function (textures, callback) {
  30300. var numRemaining = textures.length;
  30301. if (numRemaining === 0) {
  30302. callback();
  30303. return;
  30304. }
  30305. var _loop_1 = function () {
  30306. texture = textures[i];
  30307. if (texture.isReady()) {
  30308. if (--numRemaining === 0) {
  30309. callback();
  30310. }
  30311. }
  30312. else {
  30313. onLoadObservable = texture.onLoadObservable;
  30314. var onLoadCallback_1 = function () {
  30315. onLoadObservable.removeCallback(onLoadCallback_1);
  30316. if (--numRemaining === 0) {
  30317. callback();
  30318. }
  30319. };
  30320. onLoadObservable.add(onLoadCallback_1);
  30321. }
  30322. };
  30323. var texture, onLoadObservable;
  30324. for (var i = 0; i < textures.length; i++) {
  30325. _loop_1();
  30326. }
  30327. };
  30328. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30329. __decorate([
  30330. BABYLON.serialize()
  30331. ], BaseTexture.prototype, "name", void 0);
  30332. __decorate([
  30333. BABYLON.serialize("hasAlpha")
  30334. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30335. __decorate([
  30336. BABYLON.serialize()
  30337. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30338. __decorate([
  30339. BABYLON.serialize()
  30340. ], BaseTexture.prototype, "level", void 0);
  30341. __decorate([
  30342. BABYLON.serialize()
  30343. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30344. __decorate([
  30345. BABYLON.serialize("coordinatesMode")
  30346. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30347. __decorate([
  30348. BABYLON.serialize()
  30349. ], BaseTexture.prototype, "wrapU", void 0);
  30350. __decorate([
  30351. BABYLON.serialize()
  30352. ], BaseTexture.prototype, "wrapV", void 0);
  30353. __decorate([
  30354. BABYLON.serialize()
  30355. ], BaseTexture.prototype, "wrapR", void 0);
  30356. __decorate([
  30357. BABYLON.serialize()
  30358. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30359. __decorate([
  30360. BABYLON.serialize()
  30361. ], BaseTexture.prototype, "isCube", void 0);
  30362. __decorate([
  30363. BABYLON.serialize()
  30364. ], BaseTexture.prototype, "is3D", void 0);
  30365. __decorate([
  30366. BABYLON.serialize()
  30367. ], BaseTexture.prototype, "gammaSpace", void 0);
  30368. __decorate([
  30369. BABYLON.serialize()
  30370. ], BaseTexture.prototype, "invertZ", void 0);
  30371. __decorate([
  30372. BABYLON.serialize()
  30373. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30374. __decorate([
  30375. BABYLON.serialize()
  30376. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30377. __decorate([
  30378. BABYLON.serialize()
  30379. ], BaseTexture.prototype, "lodGenerationScale", null);
  30380. __decorate([
  30381. BABYLON.serialize()
  30382. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30383. return BaseTexture;
  30384. }());
  30385. BABYLON.BaseTexture = BaseTexture;
  30386. })(BABYLON || (BABYLON = {}));
  30387. //# sourceMappingURL=babylon.baseTexture.js.map
  30388. var BABYLON;
  30389. (function (BABYLON) {
  30390. var Texture = /** @class */ (function (_super) {
  30391. __extends(Texture, _super);
  30392. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30393. if (noMipmap === void 0) { noMipmap = false; }
  30394. if (invertY === void 0) { invertY = true; }
  30395. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30396. if (onLoad === void 0) { onLoad = null; }
  30397. if (onError === void 0) { onError = null; }
  30398. if (buffer === void 0) { buffer = null; }
  30399. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30400. var _this = _super.call(this, scene) || this;
  30401. _this.uOffset = 0;
  30402. _this.vOffset = 0;
  30403. _this.uScale = 1.0;
  30404. _this.vScale = 1.0;
  30405. _this.uAng = 0;
  30406. _this.vAng = 0;
  30407. _this.wAng = 0;
  30408. /**
  30409. * Defines the center of rotation (U)
  30410. */
  30411. _this.uRotationCenter = 0.5;
  30412. /**
  30413. * Defines the center of rotation (V)
  30414. */
  30415. _this.vRotationCenter = 0.5;
  30416. /**
  30417. * Defines the center of rotation (W)
  30418. */
  30419. _this.wRotationCenter = 0.5;
  30420. _this._isBlocking = true;
  30421. _this.name = url || "";
  30422. _this.url = url;
  30423. _this._noMipmap = noMipmap;
  30424. _this._invertY = invertY;
  30425. _this._samplingMode = samplingMode;
  30426. _this._buffer = buffer;
  30427. _this._deleteBuffer = deleteBuffer;
  30428. if (format) {
  30429. _this._format = format;
  30430. }
  30431. scene = _this.getScene();
  30432. if (!scene) {
  30433. return _this;
  30434. }
  30435. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30436. var load = function () {
  30437. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30438. _this.onLoadObservable.notifyObservers(_this);
  30439. }
  30440. if (onLoad) {
  30441. onLoad();
  30442. }
  30443. if (!_this.isBlocking && scene) {
  30444. scene.resetCachedMaterial();
  30445. }
  30446. };
  30447. if (!_this.url) {
  30448. _this._delayedOnLoad = load;
  30449. _this._delayedOnError = onError;
  30450. return _this;
  30451. }
  30452. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30453. if (!_this._texture) {
  30454. if (!scene.useDelayedTextureLoading) {
  30455. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30456. if (deleteBuffer) {
  30457. delete _this._buffer;
  30458. }
  30459. }
  30460. else {
  30461. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30462. _this._delayedOnLoad = load;
  30463. _this._delayedOnError = onError;
  30464. }
  30465. }
  30466. else {
  30467. if (_this._texture.isReady) {
  30468. BABYLON.Tools.SetImmediate(function () { return load(); });
  30469. }
  30470. else {
  30471. _this._texture.onLoadedObservable.add(load);
  30472. }
  30473. }
  30474. return _this;
  30475. }
  30476. Object.defineProperty(Texture.prototype, "noMipmap", {
  30477. get: function () {
  30478. return this._noMipmap;
  30479. },
  30480. enumerable: true,
  30481. configurable: true
  30482. });
  30483. Object.defineProperty(Texture.prototype, "isBlocking", {
  30484. get: function () {
  30485. return this._isBlocking;
  30486. },
  30487. set: function (value) {
  30488. this._isBlocking = value;
  30489. },
  30490. enumerable: true,
  30491. configurable: true
  30492. });
  30493. Object.defineProperty(Texture.prototype, "samplingMode", {
  30494. get: function () {
  30495. return this._samplingMode;
  30496. },
  30497. enumerable: true,
  30498. configurable: true
  30499. });
  30500. /**
  30501. * Update the url (and optional buffer) of this texture if url was null during construction.
  30502. * @param url the url of the texture
  30503. * @param buffer the buffer of the texture (defaults to null)
  30504. */
  30505. Texture.prototype.updateURL = function (url, buffer) {
  30506. if (buffer === void 0) { buffer = null; }
  30507. if (this.url) {
  30508. throw new Error("URL is already set");
  30509. }
  30510. this.url = url;
  30511. this._buffer = buffer;
  30512. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30513. this.delayLoad();
  30514. };
  30515. Texture.prototype.delayLoad = function () {
  30516. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30517. return;
  30518. }
  30519. var scene = this.getScene();
  30520. if (!scene) {
  30521. return;
  30522. }
  30523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30524. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30525. if (!this._texture) {
  30526. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30527. if (this._deleteBuffer) {
  30528. delete this._buffer;
  30529. }
  30530. }
  30531. else {
  30532. if (this._delayedOnLoad) {
  30533. if (this._texture.isReady) {
  30534. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30535. }
  30536. else {
  30537. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30538. }
  30539. }
  30540. }
  30541. this._delayedOnLoad = null;
  30542. this._delayedOnError = null;
  30543. };
  30544. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30545. if (!this._texture) {
  30546. return;
  30547. }
  30548. var scene = this.getScene();
  30549. if (!scene) {
  30550. return;
  30551. }
  30552. this._samplingMode = samplingMode;
  30553. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30554. };
  30555. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30556. x *= this.uScale;
  30557. y *= this.vScale;
  30558. x -= this.uRotationCenter * this.uScale;
  30559. y -= this.vRotationCenter * this.vScale;
  30560. z -= this.wRotationCenter;
  30561. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30562. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30563. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30564. t.z += this.wRotationCenter;
  30565. };
  30566. Texture.prototype.getTextureMatrix = function () {
  30567. var _this = this;
  30568. if (this.uOffset === this._cachedUOffset &&
  30569. this.vOffset === this._cachedVOffset &&
  30570. this.uScale === this._cachedUScale &&
  30571. this.vScale === this._cachedVScale &&
  30572. this.uAng === this._cachedUAng &&
  30573. this.vAng === this._cachedVAng &&
  30574. this.wAng === this._cachedWAng) {
  30575. return this._cachedTextureMatrix;
  30576. }
  30577. this._cachedUOffset = this.uOffset;
  30578. this._cachedVOffset = this.vOffset;
  30579. this._cachedUScale = this.uScale;
  30580. this._cachedVScale = this.vScale;
  30581. this._cachedUAng = this.uAng;
  30582. this._cachedVAng = this.vAng;
  30583. this._cachedWAng = this.wAng;
  30584. if (!this._cachedTextureMatrix) {
  30585. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30586. this._rowGenerationMatrix = new BABYLON.Matrix();
  30587. this._t0 = BABYLON.Vector3.Zero();
  30588. this._t1 = BABYLON.Vector3.Zero();
  30589. this._t2 = BABYLON.Vector3.Zero();
  30590. }
  30591. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30592. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30593. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30594. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30595. this._t1.subtractInPlace(this._t0);
  30596. this._t2.subtractInPlace(this._t0);
  30597. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30598. this._cachedTextureMatrix.m[0] = this._t1.x;
  30599. this._cachedTextureMatrix.m[1] = this._t1.y;
  30600. this._cachedTextureMatrix.m[2] = this._t1.z;
  30601. this._cachedTextureMatrix.m[4] = this._t2.x;
  30602. this._cachedTextureMatrix.m[5] = this._t2.y;
  30603. this._cachedTextureMatrix.m[6] = this._t2.z;
  30604. this._cachedTextureMatrix.m[8] = this._t0.x;
  30605. this._cachedTextureMatrix.m[9] = this._t0.y;
  30606. this._cachedTextureMatrix.m[10] = this._t0.z;
  30607. var scene = this.getScene();
  30608. if (!scene) {
  30609. return this._cachedTextureMatrix;
  30610. }
  30611. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30612. return mat.hasTexture(_this);
  30613. });
  30614. return this._cachedTextureMatrix;
  30615. };
  30616. Texture.prototype.getReflectionTextureMatrix = function () {
  30617. var _this = this;
  30618. var scene = this.getScene();
  30619. if (!scene) {
  30620. return this._cachedTextureMatrix;
  30621. }
  30622. if (this.uOffset === this._cachedUOffset &&
  30623. this.vOffset === this._cachedVOffset &&
  30624. this.uScale === this._cachedUScale &&
  30625. this.vScale === this._cachedVScale &&
  30626. this.coordinatesMode === this._cachedCoordinatesMode) {
  30627. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30628. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30629. return this._cachedTextureMatrix;
  30630. }
  30631. }
  30632. else {
  30633. return this._cachedTextureMatrix;
  30634. }
  30635. }
  30636. if (!this._cachedTextureMatrix) {
  30637. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30638. }
  30639. if (!this._projectionModeMatrix) {
  30640. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30641. }
  30642. this._cachedUOffset = this.uOffset;
  30643. this._cachedVOffset = this.vOffset;
  30644. this._cachedUScale = this.uScale;
  30645. this._cachedVScale = this.vScale;
  30646. this._cachedCoordinatesMode = this.coordinatesMode;
  30647. switch (this.coordinatesMode) {
  30648. case Texture.PLANAR_MODE:
  30649. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30650. this._cachedTextureMatrix[0] = this.uScale;
  30651. this._cachedTextureMatrix[5] = this.vScale;
  30652. this._cachedTextureMatrix[12] = this.uOffset;
  30653. this._cachedTextureMatrix[13] = this.vOffset;
  30654. break;
  30655. case Texture.PROJECTION_MODE:
  30656. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30657. this._projectionModeMatrix.m[0] = 0.5;
  30658. this._projectionModeMatrix.m[5] = -0.5;
  30659. this._projectionModeMatrix.m[10] = 0.0;
  30660. this._projectionModeMatrix.m[12] = 0.5;
  30661. this._projectionModeMatrix.m[13] = 0.5;
  30662. this._projectionModeMatrix.m[14] = 1.0;
  30663. this._projectionModeMatrix.m[15] = 1.0;
  30664. var projectionMatrix = scene.getProjectionMatrix();
  30665. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30666. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30667. break;
  30668. default:
  30669. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30670. break;
  30671. }
  30672. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30673. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30674. });
  30675. return this._cachedTextureMatrix;
  30676. };
  30677. Texture.prototype.clone = function () {
  30678. var _this = this;
  30679. return BABYLON.SerializationHelper.Clone(function () {
  30680. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30681. }, this);
  30682. };
  30683. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30684. get: function () {
  30685. if (!this._onLoadObservable) {
  30686. this._onLoadObservable = new BABYLON.Observable();
  30687. }
  30688. return this._onLoadObservable;
  30689. },
  30690. enumerable: true,
  30691. configurable: true
  30692. });
  30693. Texture.prototype.serialize = function () {
  30694. var serializationObject = _super.prototype.serialize.call(this);
  30695. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30696. serializationObject.base64String = this._buffer;
  30697. serializationObject.name = serializationObject.name.replace("data:", "");
  30698. }
  30699. serializationObject.invertY = this._invertY;
  30700. serializationObject.samplingMode = this.samplingMode;
  30701. return serializationObject;
  30702. };
  30703. Texture.prototype.getClassName = function () {
  30704. return "Texture";
  30705. };
  30706. Texture.prototype.dispose = function () {
  30707. _super.prototype.dispose.call(this);
  30708. if (this._onLoadObservable) {
  30709. this._onLoadObservable.clear();
  30710. this._onLoadObservable = null;
  30711. }
  30712. this._delayedOnLoad = null;
  30713. this._delayedOnError = null;
  30714. };
  30715. // Statics
  30716. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30717. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30718. if (onLoad === void 0) { onLoad = null; }
  30719. if (onError === void 0) { onError = null; }
  30720. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30721. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30722. };
  30723. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30724. if (parsedTexture.customType) {
  30725. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30726. // Update Sampling Mode
  30727. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30728. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30729. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30730. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30731. }
  30732. }
  30733. return parsedCustomTexture;
  30734. }
  30735. if (parsedTexture.isCube) {
  30736. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30737. }
  30738. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30739. return null;
  30740. }
  30741. var texture = BABYLON.SerializationHelper.Parse(function () {
  30742. var generateMipMaps = true;
  30743. if (parsedTexture.noMipmap) {
  30744. generateMipMaps = false;
  30745. }
  30746. if (parsedTexture.mirrorPlane) {
  30747. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30748. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30749. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30750. return mirrorTexture;
  30751. }
  30752. else if (parsedTexture.isRenderTarget) {
  30753. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30754. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30755. return renderTargetTexture;
  30756. }
  30757. else {
  30758. var texture;
  30759. if (parsedTexture.base64String) {
  30760. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30761. }
  30762. else {
  30763. var url = rootUrl + parsedTexture.name;
  30764. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30765. url = parsedTexture.url;
  30766. }
  30767. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30768. }
  30769. return texture;
  30770. }
  30771. }, parsedTexture, scene);
  30772. // Update Sampling Mode
  30773. if (parsedTexture.samplingMode) {
  30774. var sampling = parsedTexture.samplingMode;
  30775. if (texture._samplingMode !== sampling) {
  30776. texture.updateSamplingMode(sampling);
  30777. }
  30778. }
  30779. // Animations
  30780. if (parsedTexture.animations) {
  30781. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30782. var parsedAnimation = parsedTexture.animations[animationIndex];
  30783. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30784. }
  30785. }
  30786. return texture;
  30787. };
  30788. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30789. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30790. if (noMipmap === void 0) { noMipmap = false; }
  30791. if (invertY === void 0) { invertY = true; }
  30792. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30793. if (onLoad === void 0) { onLoad = null; }
  30794. if (onError === void 0) { onError = null; }
  30795. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30796. if (name.substr(0, 5) !== "data:") {
  30797. name = "data:" + name;
  30798. }
  30799. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30800. };
  30801. // Constants
  30802. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30803. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30804. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30805. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30806. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30807. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30808. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30809. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30810. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30811. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30812. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30813. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30814. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30815. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30816. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30817. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30818. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30819. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30820. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30821. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30822. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30823. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30824. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30825. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30826. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30827. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30828. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30829. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30830. /**
  30831. * 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
  30832. */
  30833. Texture.UseSerializedUrlIfAny = false;
  30834. __decorate([
  30835. BABYLON.serialize()
  30836. ], Texture.prototype, "url", void 0);
  30837. __decorate([
  30838. BABYLON.serialize()
  30839. ], Texture.prototype, "uOffset", void 0);
  30840. __decorate([
  30841. BABYLON.serialize()
  30842. ], Texture.prototype, "vOffset", void 0);
  30843. __decorate([
  30844. BABYLON.serialize()
  30845. ], Texture.prototype, "uScale", void 0);
  30846. __decorate([
  30847. BABYLON.serialize()
  30848. ], Texture.prototype, "vScale", void 0);
  30849. __decorate([
  30850. BABYLON.serialize()
  30851. ], Texture.prototype, "uAng", void 0);
  30852. __decorate([
  30853. BABYLON.serialize()
  30854. ], Texture.prototype, "vAng", void 0);
  30855. __decorate([
  30856. BABYLON.serialize()
  30857. ], Texture.prototype, "wAng", void 0);
  30858. __decorate([
  30859. BABYLON.serialize()
  30860. ], Texture.prototype, "uRotationCenter", void 0);
  30861. __decorate([
  30862. BABYLON.serialize()
  30863. ], Texture.prototype, "vRotationCenter", void 0);
  30864. __decorate([
  30865. BABYLON.serialize()
  30866. ], Texture.prototype, "wRotationCenter", void 0);
  30867. __decorate([
  30868. BABYLON.serialize()
  30869. ], Texture.prototype, "isBlocking", null);
  30870. return Texture;
  30871. }(BABYLON.BaseTexture));
  30872. BABYLON.Texture = Texture;
  30873. })(BABYLON || (BABYLON = {}));
  30874. //# sourceMappingURL=babylon.texture.js.map
  30875. var BABYLON;
  30876. (function (BABYLON) {
  30877. /**
  30878. * @hidden
  30879. **/
  30880. var _InstancesBatch = /** @class */ (function () {
  30881. function _InstancesBatch() {
  30882. this.mustReturn = false;
  30883. this.visibleInstances = new Array();
  30884. this.renderSelf = new Array();
  30885. }
  30886. return _InstancesBatch;
  30887. }());
  30888. BABYLON._InstancesBatch = _InstancesBatch;
  30889. var Mesh = /** @class */ (function (_super) {
  30890. __extends(Mesh, _super);
  30891. /**
  30892. * @constructor
  30893. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30894. * @param {Scene} scene The scene to add this mesh to.
  30895. * @param {Node} parent The parent of this mesh, if it has one
  30896. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30897. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30898. * When false, achieved by calling a clone(), also passing False.
  30899. * This will make creation of children, recursive.
  30900. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30901. */
  30902. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30903. if (scene === void 0) { scene = null; }
  30904. if (parent === void 0) { parent = null; }
  30905. if (source === void 0) { source = null; }
  30906. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30907. var _this = _super.call(this, name, scene) || this;
  30908. // Events
  30909. /**
  30910. * An event triggered before rendering the mesh
  30911. */
  30912. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30913. /**
  30914. * An event triggered after rendering the mesh
  30915. */
  30916. _this.onAfterRenderObservable = new BABYLON.Observable();
  30917. /**
  30918. * An event triggered before drawing the mesh
  30919. */
  30920. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30921. // Members
  30922. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30923. _this.instances = new Array();
  30924. _this._LODLevels = new Array();
  30925. _this._visibleInstances = {};
  30926. _this._renderIdForInstances = new Array();
  30927. _this._batchCache = new _InstancesBatch();
  30928. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30929. // Use by builder only to know what orientation were the mesh build in.
  30930. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30931. _this.overrideMaterialSideOrientation = null;
  30932. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30933. // Will be used to save a source mesh reference, If any
  30934. _this._source = null;
  30935. scene = _this.getScene();
  30936. if (source) {
  30937. // Geometry
  30938. if (source._geometry) {
  30939. source._geometry.applyToMesh(_this);
  30940. }
  30941. // Deep copy
  30942. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30943. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30944. // Source mesh
  30945. _this._source = source;
  30946. // Metadata
  30947. if (source.metadata && source.metadata.clone) {
  30948. _this.metadata = source.metadata.clone();
  30949. }
  30950. else {
  30951. _this.metadata = source.metadata;
  30952. }
  30953. // Tags
  30954. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30955. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30956. }
  30957. // Parent
  30958. _this.parent = source.parent;
  30959. // Pivot
  30960. _this.setPivotMatrix(source.getPivotMatrix());
  30961. _this.id = name + "." + source.id;
  30962. // Material
  30963. _this.material = source.material;
  30964. var index;
  30965. if (!doNotCloneChildren) {
  30966. // Children
  30967. var directDescendants = source.getDescendants(true);
  30968. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30969. var child = directDescendants[index_1];
  30970. if (child.clone) {
  30971. child.clone(name + "." + child.name, _this);
  30972. }
  30973. }
  30974. }
  30975. // Physics clone
  30976. var physicsEngine = _this.getScene().getPhysicsEngine();
  30977. if (clonePhysicsImpostor && physicsEngine) {
  30978. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30979. if (impostor) {
  30980. _this.physicsImpostor = impostor.clone(_this);
  30981. }
  30982. }
  30983. // Particles
  30984. for (index = 0; index < scene.particleSystems.length; index++) {
  30985. var system = scene.particleSystems[index];
  30986. if (system.emitter === source) {
  30987. system.clone(system.name, _this);
  30988. }
  30989. }
  30990. _this.refreshBoundingInfo();
  30991. _this.computeWorldMatrix(true);
  30992. }
  30993. // Parent
  30994. if (parent !== null) {
  30995. _this.parent = parent;
  30996. }
  30997. return _this;
  30998. }
  30999. Object.defineProperty(Mesh, "FRONTSIDE", {
  31000. /**
  31001. * Mesh side orientation : usually the external or front surface
  31002. */
  31003. get: function () {
  31004. return Mesh._FRONTSIDE;
  31005. },
  31006. enumerable: true,
  31007. configurable: true
  31008. });
  31009. Object.defineProperty(Mesh, "BACKSIDE", {
  31010. /**
  31011. * Mesh side orientation : usually the internal or back surface
  31012. */
  31013. get: function () {
  31014. return Mesh._BACKSIDE;
  31015. },
  31016. enumerable: true,
  31017. configurable: true
  31018. });
  31019. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31020. /**
  31021. * Mesh side orientation : both internal and external or front and back surfaces
  31022. */
  31023. get: function () {
  31024. return Mesh._DOUBLESIDE;
  31025. },
  31026. enumerable: true,
  31027. configurable: true
  31028. });
  31029. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31030. /**
  31031. * Mesh side orientation : by default, `FRONTSIDE`
  31032. */
  31033. get: function () {
  31034. return Mesh._DEFAULTSIDE;
  31035. },
  31036. enumerable: true,
  31037. configurable: true
  31038. });
  31039. Object.defineProperty(Mesh, "NO_CAP", {
  31040. /**
  31041. * Mesh cap setting : no cap
  31042. */
  31043. get: function () {
  31044. return Mesh._NO_CAP;
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. Object.defineProperty(Mesh, "CAP_START", {
  31050. /**
  31051. * Mesh cap setting : one cap at the beginning of the mesh
  31052. */
  31053. get: function () {
  31054. return Mesh._CAP_START;
  31055. },
  31056. enumerable: true,
  31057. configurable: true
  31058. });
  31059. Object.defineProperty(Mesh, "CAP_END", {
  31060. /**
  31061. * Mesh cap setting : one cap at the end of the mesh
  31062. */
  31063. get: function () {
  31064. return Mesh._CAP_END;
  31065. },
  31066. enumerable: true,
  31067. configurable: true
  31068. });
  31069. Object.defineProperty(Mesh, "CAP_ALL", {
  31070. /**
  31071. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31072. */
  31073. get: function () {
  31074. return Mesh._CAP_ALL;
  31075. },
  31076. enumerable: true,
  31077. configurable: true
  31078. });
  31079. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31080. set: function (callback) {
  31081. if (this._onBeforeDrawObserver) {
  31082. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31083. }
  31084. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31085. },
  31086. enumerable: true,
  31087. configurable: true
  31088. });
  31089. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31090. get: function () {
  31091. return this._morphTargetManager;
  31092. },
  31093. set: function (value) {
  31094. if (this._morphTargetManager === value) {
  31095. return;
  31096. }
  31097. this._morphTargetManager = value;
  31098. this._syncGeometryWithMorphTargetManager();
  31099. },
  31100. enumerable: true,
  31101. configurable: true
  31102. });
  31103. Object.defineProperty(Mesh.prototype, "source", {
  31104. get: function () {
  31105. return this._source;
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31111. get: function () {
  31112. return this._unIndexed;
  31113. },
  31114. set: function (value) {
  31115. if (this._unIndexed !== value) {
  31116. this._unIndexed = value;
  31117. this._markSubMeshesAsAttributesDirty();
  31118. }
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. // Methods
  31124. /**
  31125. * Returns the string "Mesh".
  31126. */
  31127. Mesh.prototype.getClassName = function () {
  31128. return "Mesh";
  31129. };
  31130. /**
  31131. * Returns a string.
  31132. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31133. */
  31134. Mesh.prototype.toString = function (fullDetails) {
  31135. var ret = _super.prototype.toString.call(this, fullDetails);
  31136. ret += ", n vertices: " + this.getTotalVertices();
  31137. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31138. if (this.animations) {
  31139. for (var i = 0; i < this.animations.length; i++) {
  31140. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31141. }
  31142. }
  31143. if (fullDetails) {
  31144. if (this._geometry) {
  31145. var ib = this.getIndices();
  31146. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31147. if (vb && ib) {
  31148. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31149. }
  31150. }
  31151. else {
  31152. ret += ", flat shading: UNKNOWN";
  31153. }
  31154. }
  31155. return ret;
  31156. };
  31157. Mesh.prototype._unBindEffect = function () {
  31158. _super.prototype._unBindEffect.call(this);
  31159. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31160. var instance = _a[_i];
  31161. instance._unBindEffect();
  31162. }
  31163. };
  31164. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31165. /**
  31166. * True if the mesh has some Levels Of Details (LOD).
  31167. * Returns a boolean.
  31168. */
  31169. get: function () {
  31170. return this._LODLevels.length > 0;
  31171. },
  31172. enumerable: true,
  31173. configurable: true
  31174. });
  31175. /**
  31176. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31177. * @returns an array of {BABYLON.MeshLODLevel}
  31178. */
  31179. Mesh.prototype.getLODLevels = function () {
  31180. return this._LODLevels;
  31181. };
  31182. Mesh.prototype._sortLODLevels = function () {
  31183. this._LODLevels.sort(function (a, b) {
  31184. if (a.distance < b.distance) {
  31185. return 1;
  31186. }
  31187. if (a.distance > b.distance) {
  31188. return -1;
  31189. }
  31190. return 0;
  31191. });
  31192. };
  31193. /**
  31194. * Add a mesh as LOD level triggered at the given distance.
  31195. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31196. * @param distance The distance from the center of the object to show this level
  31197. * @param mesh The mesh to be added as LOD level (can be null)
  31198. * @return This mesh (for chaining)
  31199. */
  31200. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31201. if (mesh && mesh._masterMesh) {
  31202. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31203. return this;
  31204. }
  31205. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31206. this._LODLevels.push(level);
  31207. if (mesh) {
  31208. mesh._masterMesh = this;
  31209. }
  31210. this._sortLODLevels();
  31211. return this;
  31212. };
  31213. /**
  31214. * Returns the LOD level mesh at the passed distance or null if not found.
  31215. * It is related to the method `addLODLevel(distance, mesh)`.
  31216. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31217. * Returns an object Mesh or `null`.
  31218. */
  31219. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31220. for (var index = 0; index < this._LODLevels.length; index++) {
  31221. var level = this._LODLevels[index];
  31222. if (level.distance === distance) {
  31223. return level.mesh;
  31224. }
  31225. }
  31226. return null;
  31227. };
  31228. /**
  31229. * Remove a mesh from the LOD array
  31230. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31231. * @param {Mesh} mesh The mesh to be removed.
  31232. * @return {Mesh} This mesh (for chaining)
  31233. */
  31234. Mesh.prototype.removeLODLevel = function (mesh) {
  31235. for (var index = 0; index < this._LODLevels.length; index++) {
  31236. if (this._LODLevels[index].mesh === mesh) {
  31237. this._LODLevels.splice(index, 1);
  31238. if (mesh) {
  31239. mesh._masterMesh = null;
  31240. }
  31241. }
  31242. }
  31243. this._sortLODLevels();
  31244. return this;
  31245. };
  31246. /**
  31247. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31248. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31249. */
  31250. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31251. if (!this._LODLevels || this._LODLevels.length === 0) {
  31252. return this;
  31253. }
  31254. var bSphere;
  31255. if (boundingSphere) {
  31256. bSphere = boundingSphere;
  31257. }
  31258. else {
  31259. var boundingInfo = this.getBoundingInfo();
  31260. bSphere = boundingInfo.boundingSphere;
  31261. }
  31262. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31263. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31264. if (this.onLODLevelSelection) {
  31265. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31266. }
  31267. return this;
  31268. }
  31269. for (var index = 0; index < this._LODLevels.length; index++) {
  31270. var level = this._LODLevels[index];
  31271. if (level.distance < distanceToCamera) {
  31272. if (level.mesh) {
  31273. level.mesh._preActivate();
  31274. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31275. }
  31276. if (this.onLODLevelSelection) {
  31277. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31278. }
  31279. return level.mesh;
  31280. }
  31281. }
  31282. if (this.onLODLevelSelection) {
  31283. this.onLODLevelSelection(distanceToCamera, this, this);
  31284. }
  31285. return this;
  31286. };
  31287. Object.defineProperty(Mesh.prototype, "geometry", {
  31288. /**
  31289. * Returns the mesh internal Geometry object.
  31290. */
  31291. get: function () {
  31292. return this._geometry;
  31293. },
  31294. enumerable: true,
  31295. configurable: true
  31296. });
  31297. /**
  31298. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31299. */
  31300. Mesh.prototype.getTotalVertices = function () {
  31301. if (this._geometry === null || this._geometry === undefined) {
  31302. return 0;
  31303. }
  31304. return this._geometry.getTotalVertices();
  31305. };
  31306. /**
  31307. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31308. * 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.
  31309. * You can force the copy with forceCopy === true
  31310. * Returns null if the mesh has no geometry or no vertex buffer.
  31311. * Possible `kind` values :
  31312. * - BABYLON.VertexBuffer.PositionKind
  31313. * - BABYLON.VertexBuffer.UVKind
  31314. * - BABYLON.VertexBuffer.UV2Kind
  31315. * - BABYLON.VertexBuffer.UV3Kind
  31316. * - BABYLON.VertexBuffer.UV4Kind
  31317. * - BABYLON.VertexBuffer.UV5Kind
  31318. * - BABYLON.VertexBuffer.UV6Kind
  31319. * - BABYLON.VertexBuffer.ColorKind
  31320. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31321. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31322. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31323. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31324. */
  31325. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31326. if (!this._geometry) {
  31327. return null;
  31328. }
  31329. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31330. };
  31331. /**
  31332. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31333. * Returns `null` if the mesh has no geometry.
  31334. * Possible `kind` values :
  31335. * - BABYLON.VertexBuffer.PositionKind
  31336. * - BABYLON.VertexBuffer.UVKind
  31337. * - BABYLON.VertexBuffer.UV2Kind
  31338. * - BABYLON.VertexBuffer.UV3Kind
  31339. * - BABYLON.VertexBuffer.UV4Kind
  31340. * - BABYLON.VertexBuffer.UV5Kind
  31341. * - BABYLON.VertexBuffer.UV6Kind
  31342. * - BABYLON.VertexBuffer.ColorKind
  31343. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31344. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31345. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31346. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31347. */
  31348. Mesh.prototype.getVertexBuffer = function (kind) {
  31349. if (!this._geometry) {
  31350. return null;
  31351. }
  31352. return this._geometry.getVertexBuffer(kind);
  31353. };
  31354. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31355. if (!this._geometry) {
  31356. if (this._delayInfo) {
  31357. return this._delayInfo.indexOf(kind) !== -1;
  31358. }
  31359. return false;
  31360. }
  31361. return this._geometry.isVerticesDataPresent(kind);
  31362. };
  31363. /**
  31364. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31365. * Possible `kind` values :
  31366. * - BABYLON.VertexBuffer.PositionKind
  31367. * - BABYLON.VertexBuffer.UVKind
  31368. * - BABYLON.VertexBuffer.UV2Kind
  31369. * - BABYLON.VertexBuffer.UV3Kind
  31370. * - BABYLON.VertexBuffer.UV4Kind
  31371. * - BABYLON.VertexBuffer.UV5Kind
  31372. * - BABYLON.VertexBuffer.UV6Kind
  31373. * - BABYLON.VertexBuffer.ColorKind
  31374. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31375. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31376. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31377. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31378. */
  31379. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31380. if (!this._geometry) {
  31381. if (this._delayInfo) {
  31382. return this._delayInfo.indexOf(kind) !== -1;
  31383. }
  31384. return false;
  31385. }
  31386. return this._geometry.isVertexBufferUpdatable(kind);
  31387. };
  31388. /**
  31389. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31390. * Possible `kind` values :
  31391. * - BABYLON.VertexBuffer.PositionKind
  31392. * - BABYLON.VertexBuffer.UVKind
  31393. * - BABYLON.VertexBuffer.UV2Kind
  31394. * - BABYLON.VertexBuffer.UV3Kind
  31395. * - BABYLON.VertexBuffer.UV4Kind
  31396. * - BABYLON.VertexBuffer.UV5Kind
  31397. * - BABYLON.VertexBuffer.UV6Kind
  31398. * - BABYLON.VertexBuffer.ColorKind
  31399. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31400. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31401. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31402. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31403. */
  31404. Mesh.prototype.getVerticesDataKinds = function () {
  31405. if (!this._geometry) {
  31406. var result = new Array();
  31407. if (this._delayInfo) {
  31408. this._delayInfo.forEach(function (kind, index, array) {
  31409. result.push(kind);
  31410. });
  31411. }
  31412. return result;
  31413. }
  31414. return this._geometry.getVerticesDataKinds();
  31415. };
  31416. /**
  31417. * Returns a positive integer : the total number of indices in this mesh geometry.
  31418. * Returns zero if the mesh has no geometry.
  31419. */
  31420. Mesh.prototype.getTotalIndices = function () {
  31421. if (!this._geometry) {
  31422. return 0;
  31423. }
  31424. return this._geometry.getTotalIndices();
  31425. };
  31426. /**
  31427. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31428. * 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.
  31429. * Returns an empty array if the mesh has no geometry.
  31430. */
  31431. Mesh.prototype.getIndices = function (copyWhenShared) {
  31432. if (!this._geometry) {
  31433. return [];
  31434. }
  31435. return this._geometry.getIndices(copyWhenShared);
  31436. };
  31437. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31438. get: function () {
  31439. return this._masterMesh !== null && this._masterMesh !== undefined;
  31440. },
  31441. enumerable: true,
  31442. configurable: true
  31443. });
  31444. /**
  31445. * Determine if the current mesh is ready to be rendered
  31446. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31447. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31448. * @returns true if all associated assets are ready (material, textures, shaders)
  31449. */
  31450. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31451. if (completeCheck === void 0) { completeCheck = false; }
  31452. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31453. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31454. return false;
  31455. }
  31456. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31457. return false;
  31458. }
  31459. if (!this.subMeshes || this.subMeshes.length === 0) {
  31460. return true;
  31461. }
  31462. if (!completeCheck) {
  31463. return true;
  31464. }
  31465. var engine = this.getEngine();
  31466. var scene = this.getScene();
  31467. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31468. this.computeWorldMatrix();
  31469. var mat = this.material || scene.defaultMaterial;
  31470. if (mat) {
  31471. if (mat.storeEffectOnSubMeshes) {
  31472. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31473. var subMesh = _a[_i];
  31474. var effectiveMaterial = subMesh.getMaterial();
  31475. if (effectiveMaterial) {
  31476. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31477. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31478. return false;
  31479. }
  31480. }
  31481. else {
  31482. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31483. return false;
  31484. }
  31485. }
  31486. }
  31487. }
  31488. }
  31489. else {
  31490. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31491. return false;
  31492. }
  31493. }
  31494. }
  31495. // Shadows
  31496. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31497. var light = _c[_b];
  31498. var generator = light.getShadowGenerator();
  31499. if (generator) {
  31500. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31501. var subMesh = _e[_d];
  31502. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31503. return false;
  31504. }
  31505. }
  31506. }
  31507. }
  31508. // LOD
  31509. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31510. var lod = _g[_f];
  31511. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31512. return false;
  31513. }
  31514. }
  31515. return true;
  31516. };
  31517. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31518. /**
  31519. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31520. * This property is pertinent only for updatable parametric shapes.
  31521. */
  31522. get: function () {
  31523. return this._areNormalsFrozen;
  31524. },
  31525. enumerable: true,
  31526. configurable: true
  31527. });
  31528. /**
  31529. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31530. * It has no effect at all on other shapes.
  31531. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31532. * Returns the Mesh.
  31533. */
  31534. Mesh.prototype.freezeNormals = function () {
  31535. this._areNormalsFrozen = true;
  31536. return this;
  31537. };
  31538. /**
  31539. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31540. * It has no effect at all on other shapes.
  31541. * It reactivates the mesh normals computation if it was previously frozen.
  31542. * Returns the Mesh.
  31543. */
  31544. Mesh.prototype.unfreezeNormals = function () {
  31545. this._areNormalsFrozen = false;
  31546. return this;
  31547. };
  31548. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31549. /**
  31550. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31551. */
  31552. set: function (count) {
  31553. this._overridenInstanceCount = count;
  31554. },
  31555. enumerable: true,
  31556. configurable: true
  31557. });
  31558. // Methods
  31559. Mesh.prototype._preActivate = function () {
  31560. var sceneRenderId = this.getScene().getRenderId();
  31561. if (this._preActivateId === sceneRenderId) {
  31562. return this;
  31563. }
  31564. this._preActivateId = sceneRenderId;
  31565. this._visibleInstances = null;
  31566. return this;
  31567. };
  31568. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31569. if (this._visibleInstances) {
  31570. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31571. }
  31572. return this;
  31573. };
  31574. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31575. if (!this._visibleInstances) {
  31576. this._visibleInstances = {};
  31577. this._visibleInstances.defaultRenderId = renderId;
  31578. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31579. }
  31580. if (!this._visibleInstances[renderId]) {
  31581. this._visibleInstances[renderId] = new Array();
  31582. }
  31583. this._visibleInstances[renderId].push(instance);
  31584. return this;
  31585. };
  31586. /**
  31587. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31588. * This means the mesh underlying bounding box and sphere are recomputed.
  31589. * Returns the Mesh.
  31590. */
  31591. Mesh.prototype.refreshBoundingInfo = function () {
  31592. return this._refreshBoundingInfo(false);
  31593. };
  31594. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31595. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31596. return this;
  31597. }
  31598. var data = this._getPositionData(applySkeleton);
  31599. if (data) {
  31600. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31601. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31602. }
  31603. if (this.subMeshes) {
  31604. for (var index = 0; index < this.subMeshes.length; index++) {
  31605. this.subMeshes[index].refreshBoundingInfo();
  31606. }
  31607. }
  31608. this._updateBoundingInfo();
  31609. return this;
  31610. };
  31611. Mesh.prototype._getPositionData = function (applySkeleton) {
  31612. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31613. if (data && applySkeleton && this.skeleton) {
  31614. data = BABYLON.Tools.Slice(data);
  31615. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31616. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31617. if (matricesWeightsData && matricesIndicesData) {
  31618. var needExtras = this.numBoneInfluencers > 4;
  31619. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31620. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31621. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31622. var tempVector = BABYLON.Tmp.Vector3[0];
  31623. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31624. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31625. var matWeightIdx = 0;
  31626. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31627. finalMatrix.reset();
  31628. var inf;
  31629. var weight;
  31630. for (inf = 0; inf < 4; inf++) {
  31631. weight = matricesWeightsData[matWeightIdx + inf];
  31632. if (weight > 0) {
  31633. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31634. finalMatrix.addToSelf(tempMatrix);
  31635. }
  31636. }
  31637. if (needExtras) {
  31638. for (inf = 0; inf < 4; inf++) {
  31639. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31640. if (weight > 0) {
  31641. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31642. finalMatrix.addToSelf(tempMatrix);
  31643. }
  31644. }
  31645. }
  31646. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31647. tempVector.toArray(data, index);
  31648. }
  31649. }
  31650. }
  31651. return data;
  31652. };
  31653. Mesh.prototype._createGlobalSubMesh = function (force) {
  31654. var totalVertices = this.getTotalVertices();
  31655. if (!totalVertices || !this.getIndices()) {
  31656. return null;
  31657. }
  31658. // Check if we need to recreate the submeshes
  31659. if (this.subMeshes && this.subMeshes.length > 0) {
  31660. var ib = this.getIndices();
  31661. if (!ib) {
  31662. return null;
  31663. }
  31664. var totalIndices = ib.length;
  31665. var needToRecreate = false;
  31666. if (force) {
  31667. needToRecreate = true;
  31668. }
  31669. else {
  31670. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31671. var submesh = _a[_i];
  31672. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31673. needToRecreate = true;
  31674. break;
  31675. }
  31676. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31677. needToRecreate = true;
  31678. break;
  31679. }
  31680. }
  31681. }
  31682. if (!needToRecreate) {
  31683. return this.subMeshes[0];
  31684. }
  31685. }
  31686. this.releaseSubMeshes();
  31687. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31688. };
  31689. Mesh.prototype.subdivide = function (count) {
  31690. if (count < 1) {
  31691. return;
  31692. }
  31693. var totalIndices = this.getTotalIndices();
  31694. var subdivisionSize = (totalIndices / count) | 0;
  31695. var offset = 0;
  31696. // Ensure that subdivisionSize is a multiple of 3
  31697. while (subdivisionSize % 3 !== 0) {
  31698. subdivisionSize++;
  31699. }
  31700. this.releaseSubMeshes();
  31701. for (var index = 0; index < count; index++) {
  31702. if (offset >= totalIndices) {
  31703. break;
  31704. }
  31705. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31706. offset += subdivisionSize;
  31707. }
  31708. this.synchronizeInstances();
  31709. };
  31710. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31711. if (updatable === void 0) { updatable = false; }
  31712. if (!this._geometry) {
  31713. var vertexData = new BABYLON.VertexData();
  31714. vertexData.set(data, kind);
  31715. var scene = this.getScene();
  31716. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31717. }
  31718. else {
  31719. this._geometry.setVerticesData(kind, data, updatable, stride);
  31720. }
  31721. return this;
  31722. };
  31723. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31724. if (updatable === void 0) { updatable = true; }
  31725. var vb = this.getVertexBuffer(kind);
  31726. if (!vb || vb.isUpdatable() === updatable) {
  31727. return;
  31728. }
  31729. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31730. };
  31731. /**
  31732. * Sets the mesh VertexBuffer.
  31733. * Returns the Mesh.
  31734. */
  31735. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31736. if (!this._geometry) {
  31737. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31738. }
  31739. this._geometry.setVerticesBuffer(buffer);
  31740. return this;
  31741. };
  31742. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31743. if (!this._geometry) {
  31744. return this;
  31745. }
  31746. if (!makeItUnique) {
  31747. this._geometry.updateVerticesData(kind, data, updateExtends);
  31748. }
  31749. else {
  31750. this.makeGeometryUnique();
  31751. this.updateVerticesData(kind, data, updateExtends, false);
  31752. }
  31753. return this;
  31754. };
  31755. /**
  31756. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31757. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31758. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31759. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31760. * Returns the Mesh.
  31761. */
  31762. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31763. if (computeNormals === void 0) { computeNormals = true; }
  31764. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31765. if (!positions) {
  31766. return this;
  31767. }
  31768. positionFunction(positions);
  31769. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31770. if (computeNormals) {
  31771. var indices = this.getIndices();
  31772. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31773. if (!normals) {
  31774. return this;
  31775. }
  31776. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31777. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31778. }
  31779. return this;
  31780. };
  31781. /**
  31782. * Creates a un-shared specific occurence of the geometry for the mesh.
  31783. * Returns the Mesh.
  31784. */
  31785. Mesh.prototype.makeGeometryUnique = function () {
  31786. if (!this._geometry) {
  31787. return this;
  31788. }
  31789. var oldGeometry = this._geometry;
  31790. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31791. oldGeometry.releaseForMesh(this, true);
  31792. geometry.applyToMesh(this);
  31793. return this;
  31794. };
  31795. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31796. if (totalVertices === void 0) { totalVertices = null; }
  31797. if (updatable === void 0) { updatable = false; }
  31798. if (!this._geometry) {
  31799. var vertexData = new BABYLON.VertexData();
  31800. vertexData.indices = indices;
  31801. var scene = this.getScene();
  31802. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31803. }
  31804. else {
  31805. this._geometry.setIndices(indices, totalVertices, updatable);
  31806. }
  31807. return this;
  31808. };
  31809. /**
  31810. * Update the current index buffer
  31811. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31812. * Returns the Mesh.
  31813. */
  31814. Mesh.prototype.updateIndices = function (indices, offset) {
  31815. if (!this._geometry) {
  31816. return this;
  31817. }
  31818. this._geometry.updateIndices(indices, offset);
  31819. return this;
  31820. };
  31821. /**
  31822. * Invert the geometry to move from a right handed system to a left handed one.
  31823. * Returns the Mesh.
  31824. */
  31825. Mesh.prototype.toLeftHanded = function () {
  31826. if (!this._geometry) {
  31827. return this;
  31828. }
  31829. this._geometry.toLeftHanded();
  31830. return this;
  31831. };
  31832. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31833. if (!this._geometry) {
  31834. return this;
  31835. }
  31836. var engine = this.getScene().getEngine();
  31837. // Wireframe
  31838. var indexToBind;
  31839. if (this._unIndexed) {
  31840. indexToBind = null;
  31841. }
  31842. else {
  31843. switch (fillMode) {
  31844. case BABYLON.Material.PointFillMode:
  31845. indexToBind = null;
  31846. break;
  31847. case BABYLON.Material.WireFrameFillMode:
  31848. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31849. break;
  31850. default:
  31851. case BABYLON.Material.TriangleFillMode:
  31852. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31853. break;
  31854. }
  31855. }
  31856. // VBOs
  31857. this._geometry._bind(effect, indexToBind);
  31858. return this;
  31859. };
  31860. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31861. if (alternate === void 0) { alternate = false; }
  31862. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31863. return this;
  31864. }
  31865. this.onBeforeDrawObservable.notifyObservers(this);
  31866. var scene = this.getScene();
  31867. var engine = scene.getEngine();
  31868. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31869. // or triangles as points
  31870. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31871. }
  31872. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31873. // Triangles as wireframe
  31874. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31875. }
  31876. else {
  31877. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31878. }
  31879. if (scene._isAlternateRenderingEnabled && !alternate) {
  31880. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31881. if (!effect || !scene.activeCamera) {
  31882. return this;
  31883. }
  31884. scene._switchToAlternateCameraConfiguration(true);
  31885. this._effectiveMaterial.bindView(effect);
  31886. this._effectiveMaterial.bindViewProjection(effect);
  31887. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31888. this._draw(subMesh, fillMode, instancesCount, true);
  31889. engine.setViewport(scene.activeCamera.viewport);
  31890. scene._switchToAlternateCameraConfiguration(false);
  31891. this._effectiveMaterial.bindView(effect);
  31892. this._effectiveMaterial.bindViewProjection(effect);
  31893. }
  31894. return this;
  31895. };
  31896. /**
  31897. * Registers for this mesh a javascript function called just before the rendering process.
  31898. * This function is passed the current mesh.
  31899. * Return the Mesh.
  31900. */
  31901. Mesh.prototype.registerBeforeRender = function (func) {
  31902. this.onBeforeRenderObservable.add(func);
  31903. return this;
  31904. };
  31905. /**
  31906. * Disposes a previously registered javascript function called before the rendering.
  31907. * This function is passed the current mesh.
  31908. * Returns the Mesh.
  31909. */
  31910. Mesh.prototype.unregisterBeforeRender = function (func) {
  31911. this.onBeforeRenderObservable.removeCallback(func);
  31912. return this;
  31913. };
  31914. /**
  31915. * Registers for this mesh a javascript function called just after the rendering is complete.
  31916. * This function is passed the current mesh.
  31917. * Returns the Mesh.
  31918. */
  31919. Mesh.prototype.registerAfterRender = function (func) {
  31920. this.onAfterRenderObservable.add(func);
  31921. return this;
  31922. };
  31923. /**
  31924. * Disposes a previously registered javascript function called after the rendering.
  31925. * This function is passed the current mesh.
  31926. * Return the Mesh.
  31927. */
  31928. Mesh.prototype.unregisterAfterRender = function (func) {
  31929. this.onAfterRenderObservable.removeCallback(func);
  31930. return this;
  31931. };
  31932. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31933. var scene = this.getScene();
  31934. this._batchCache.mustReturn = false;
  31935. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31936. this._batchCache.visibleInstances[subMeshId] = null;
  31937. if (this._visibleInstances) {
  31938. var currentRenderId = scene.getRenderId();
  31939. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31940. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31941. var selfRenderId = this._renderId;
  31942. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31943. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31944. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31945. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31946. }
  31947. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31948. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31949. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31950. this._batchCache.mustReturn = true;
  31951. return this._batchCache;
  31952. }
  31953. if (currentRenderId !== selfRenderId) {
  31954. this._batchCache.renderSelf[subMeshId] = false;
  31955. }
  31956. }
  31957. this._renderIdForInstances[subMeshId] = currentRenderId;
  31958. }
  31959. return this._batchCache;
  31960. };
  31961. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31962. var visibleInstances = batch.visibleInstances[subMesh._id];
  31963. if (!visibleInstances) {
  31964. return this;
  31965. }
  31966. var matricesCount = visibleInstances.length + 1;
  31967. var bufferSize = matricesCount * 16 * 4;
  31968. var currentInstancesBufferSize = this._instancesBufferSize;
  31969. var instancesBuffer = this._instancesBuffer;
  31970. while (this._instancesBufferSize < bufferSize) {
  31971. this._instancesBufferSize *= 2;
  31972. }
  31973. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31974. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31975. }
  31976. var offset = 0;
  31977. var instancesCount = 0;
  31978. var world = this.getWorldMatrix();
  31979. if (batch.renderSelf[subMesh._id]) {
  31980. world.copyToArray(this._instancesData, offset);
  31981. offset += 16;
  31982. instancesCount++;
  31983. }
  31984. if (visibleInstances) {
  31985. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31986. var instance = visibleInstances[instanceIndex];
  31987. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31988. offset += 16;
  31989. instancesCount++;
  31990. }
  31991. }
  31992. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31993. if (instancesBuffer) {
  31994. instancesBuffer.dispose();
  31995. }
  31996. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31997. this._instancesBuffer = instancesBuffer;
  31998. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31999. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32000. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32001. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32002. }
  32003. else {
  32004. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32005. }
  32006. this._bind(subMesh, effect, fillMode);
  32007. this._draw(subMesh, fillMode, instancesCount);
  32008. engine.unbindInstanceAttributes();
  32009. return this;
  32010. };
  32011. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32012. var scene = this.getScene();
  32013. var engine = scene.getEngine();
  32014. if (hardwareInstancedRendering) {
  32015. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32016. }
  32017. else {
  32018. if (batch.renderSelf[subMesh._id]) {
  32019. // Draw
  32020. if (onBeforeDraw) {
  32021. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32022. }
  32023. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32024. }
  32025. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32026. if (visibleInstancesForSubMesh) {
  32027. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32028. var instance = visibleInstancesForSubMesh[instanceIndex];
  32029. // World
  32030. var world = instance.getWorldMatrix();
  32031. if (onBeforeDraw) {
  32032. onBeforeDraw(true, world, effectiveMaterial);
  32033. }
  32034. // Draw
  32035. this._draw(subMesh, fillMode);
  32036. }
  32037. }
  32038. }
  32039. return this;
  32040. };
  32041. /**
  32042. * 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
  32043. * @param subMesh defines the subMesh to render
  32044. * @param enableAlphaMode defines if alpha mode can be changed
  32045. * @returns the current mesh
  32046. */
  32047. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32048. this._checkOcclusionQuery();
  32049. if (this._isOccluded) {
  32050. return this;
  32051. }
  32052. var scene = this.getScene();
  32053. // Managing instances
  32054. var batch = this._getInstancesRenderList(subMesh._id);
  32055. if (batch.mustReturn) {
  32056. return this;
  32057. }
  32058. // Checking geometry state
  32059. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32060. return this;
  32061. }
  32062. this.onBeforeRenderObservable.notifyObservers(this);
  32063. var engine = scene.getEngine();
  32064. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32065. // Material
  32066. var material = subMesh.getMaterial();
  32067. if (!material) {
  32068. return this;
  32069. }
  32070. this._effectiveMaterial = material;
  32071. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32072. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32073. return this;
  32074. }
  32075. }
  32076. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32077. return this;
  32078. }
  32079. // Alpha mode
  32080. if (enableAlphaMode) {
  32081. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32082. }
  32083. // Outline - step 1
  32084. var savedDepthWrite = engine.getDepthWrite();
  32085. if (this.renderOutline) {
  32086. engine.setDepthWrite(false);
  32087. scene.getOutlineRenderer().render(subMesh, batch);
  32088. engine.setDepthWrite(savedDepthWrite);
  32089. }
  32090. var effect;
  32091. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32092. effect = subMesh.effect;
  32093. }
  32094. else {
  32095. effect = this._effectiveMaterial.getEffect();
  32096. }
  32097. if (!effect) {
  32098. return this;
  32099. }
  32100. var sideOrientation = this.overrideMaterialSideOrientation;
  32101. if (sideOrientation == null) {
  32102. sideOrientation = this._effectiveMaterial.sideOrientation;
  32103. if (this._getWorldMatrixDeterminant() < 0) {
  32104. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32105. }
  32106. }
  32107. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32108. if (this._effectiveMaterial.forceDepthWrite) {
  32109. engine.setDepthWrite(true);
  32110. }
  32111. // Bind
  32112. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32113. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32114. this._bind(subMesh, effect, fillMode);
  32115. }
  32116. var world = this.getWorldMatrix();
  32117. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32118. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32119. }
  32120. else {
  32121. this._effectiveMaterial.bind(world, this);
  32122. }
  32123. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32124. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32125. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32126. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32127. }
  32128. // Draw
  32129. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32130. // Unbind
  32131. this._effectiveMaterial.unbind();
  32132. // Outline - step 2
  32133. if (this.renderOutline && savedDepthWrite) {
  32134. engine.setDepthWrite(true);
  32135. engine.setColorWrite(false);
  32136. scene.getOutlineRenderer().render(subMesh, batch);
  32137. engine.setColorWrite(true);
  32138. }
  32139. // Overlay
  32140. if (this.renderOverlay) {
  32141. var currentMode = engine.getAlphaMode();
  32142. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32143. scene.getOutlineRenderer().render(subMesh, batch, true);
  32144. engine.setAlphaMode(currentMode);
  32145. }
  32146. this.onAfterRenderObservable.notifyObservers(this);
  32147. return this;
  32148. };
  32149. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32150. if (isInstance && effectiveMaterial) {
  32151. effectiveMaterial.bindOnlyWorldMatrix(world);
  32152. }
  32153. };
  32154. /**
  32155. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32156. */
  32157. Mesh.prototype.getEmittedParticleSystems = function () {
  32158. var results = new Array();
  32159. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32160. var particleSystem = this.getScene().particleSystems[index];
  32161. if (particleSystem.emitter === this) {
  32162. results.push(particleSystem);
  32163. }
  32164. }
  32165. return results;
  32166. };
  32167. /**
  32168. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32169. */
  32170. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32171. var results = new Array();
  32172. var descendants = this.getDescendants();
  32173. descendants.push(this);
  32174. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32175. var particleSystem = this.getScene().particleSystems[index];
  32176. var emitter = particleSystem.emitter;
  32177. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32178. results.push(particleSystem);
  32179. }
  32180. }
  32181. return results;
  32182. };
  32183. /**
  32184. * Normalize matrix weights so that all vertices have a total weight set to 1
  32185. */
  32186. Mesh.prototype.cleanMatrixWeights = function () {
  32187. var epsilon = 1e-3;
  32188. var noInfluenceBoneIndex = 0.0;
  32189. if (this.skeleton) {
  32190. noInfluenceBoneIndex = this.skeleton.bones.length;
  32191. }
  32192. else {
  32193. return;
  32194. }
  32195. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32196. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32197. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32198. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32199. var influencers = this.numBoneInfluencers;
  32200. var size = matricesWeights.length;
  32201. for (var i = 0; i < size; i += 4) {
  32202. var weight = 0.0;
  32203. var firstZeroWeight = -1;
  32204. for (var j = 0; j < 4; j++) {
  32205. var w = matricesWeights[i + j];
  32206. weight += w;
  32207. if (w < epsilon && firstZeroWeight < 0) {
  32208. firstZeroWeight = j;
  32209. }
  32210. }
  32211. if (matricesWeightsExtra) {
  32212. for (var j = 0; j < 4; j++) {
  32213. var w = matricesWeightsExtra[i + j];
  32214. weight += w;
  32215. if (w < epsilon && firstZeroWeight < 0) {
  32216. firstZeroWeight = j + 4;
  32217. }
  32218. }
  32219. }
  32220. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32221. firstZeroWeight = influencers - 1;
  32222. }
  32223. if (weight > epsilon) {
  32224. var mweight = 1.0 / weight;
  32225. for (var j = 0; j < 4; j++) {
  32226. matricesWeights[i + j] *= mweight;
  32227. }
  32228. if (matricesWeightsExtra) {
  32229. for (var j = 0; j < 4; j++) {
  32230. matricesWeightsExtra[i + j] *= mweight;
  32231. }
  32232. }
  32233. }
  32234. else {
  32235. if (firstZeroWeight >= 4) {
  32236. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32237. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32238. }
  32239. else {
  32240. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32241. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32242. }
  32243. }
  32244. }
  32245. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32246. if (matricesIndicesExtra) {
  32247. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32248. }
  32249. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32250. if (matricesWeightsExtra) {
  32251. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32252. }
  32253. };
  32254. Mesh.prototype._checkDelayState = function () {
  32255. var scene = this.getScene();
  32256. if (this._geometry) {
  32257. this._geometry.load(scene);
  32258. }
  32259. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32260. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32261. this._queueLoad(scene);
  32262. }
  32263. return this;
  32264. };
  32265. Mesh.prototype._queueLoad = function (scene) {
  32266. var _this = this;
  32267. scene._addPendingData(this);
  32268. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32269. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32270. if (data instanceof ArrayBuffer) {
  32271. _this._delayLoadingFunction(data, _this);
  32272. }
  32273. else {
  32274. _this._delayLoadingFunction(JSON.parse(data), _this);
  32275. }
  32276. _this.instances.forEach(function (instance) {
  32277. instance._syncSubMeshes();
  32278. });
  32279. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32280. scene._removePendingData(_this);
  32281. }, function () { }, scene.database, getBinaryData);
  32282. return this;
  32283. };
  32284. /**
  32285. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32286. */
  32287. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32288. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32289. return false;
  32290. }
  32291. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32292. return false;
  32293. }
  32294. this._checkDelayState();
  32295. return true;
  32296. };
  32297. /**
  32298. * Sets the mesh material by the material or multiMaterial `id` property.
  32299. * The material `id` is a string identifying the material or the multiMaterial.
  32300. * This method returns the Mesh.
  32301. */
  32302. Mesh.prototype.setMaterialByID = function (id) {
  32303. var materials = this.getScene().materials;
  32304. var index;
  32305. for (index = materials.length - 1; index > -1; index--) {
  32306. if (materials[index].id === id) {
  32307. this.material = materials[index];
  32308. return this;
  32309. }
  32310. }
  32311. // Multi
  32312. var multiMaterials = this.getScene().multiMaterials;
  32313. for (index = multiMaterials.length - 1; index > -1; index--) {
  32314. if (multiMaterials[index].id === id) {
  32315. this.material = multiMaterials[index];
  32316. return this;
  32317. }
  32318. }
  32319. return this;
  32320. };
  32321. /**
  32322. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32323. */
  32324. Mesh.prototype.getAnimatables = function () {
  32325. var results = new Array();
  32326. if (this.material) {
  32327. results.push(this.material);
  32328. }
  32329. if (this.skeleton) {
  32330. results.push(this.skeleton);
  32331. }
  32332. return results;
  32333. };
  32334. /**
  32335. * Modifies the mesh geometry according to the passed transformation matrix.
  32336. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32337. * The mesh normals are modified accordingly the same transformation.
  32338. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32339. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32340. * Returns the Mesh.
  32341. */
  32342. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32343. // Position
  32344. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32345. return this;
  32346. }
  32347. var submeshes = this.subMeshes.splice(0);
  32348. this._resetPointsArrayCache();
  32349. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32350. var temp = new Array();
  32351. var index;
  32352. for (index = 0; index < data.length; index += 3) {
  32353. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32354. }
  32355. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32356. // Normals
  32357. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32358. return this;
  32359. }
  32360. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32361. temp = [];
  32362. for (index = 0; index < data.length; index += 3) {
  32363. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32364. }
  32365. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32366. // flip faces?
  32367. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32368. this.flipFaces();
  32369. }
  32370. // Restore submeshes
  32371. this.releaseSubMeshes();
  32372. this.subMeshes = submeshes;
  32373. return this;
  32374. };
  32375. /**
  32376. * Modifies the mesh geometry according to its own current World Matrix.
  32377. * The mesh World Matrix is then reset.
  32378. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32379. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32380. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32381. * Returns the Mesh.
  32382. */
  32383. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32384. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32385. this.scaling.copyFromFloats(1, 1, 1);
  32386. this.position.copyFromFloats(0, 0, 0);
  32387. this.rotation.copyFromFloats(0, 0, 0);
  32388. //only if quaternion is already set
  32389. if (this.rotationQuaternion) {
  32390. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32391. }
  32392. this._worldMatrix = BABYLON.Matrix.Identity();
  32393. return this;
  32394. };
  32395. Object.defineProperty(Mesh.prototype, "_positions", {
  32396. // Cache
  32397. get: function () {
  32398. if (this._geometry) {
  32399. return this._geometry._positions;
  32400. }
  32401. return null;
  32402. },
  32403. enumerable: true,
  32404. configurable: true
  32405. });
  32406. Mesh.prototype._resetPointsArrayCache = function () {
  32407. if (this._geometry) {
  32408. this._geometry._resetPointsArrayCache();
  32409. }
  32410. return this;
  32411. };
  32412. Mesh.prototype._generatePointsArray = function () {
  32413. if (this._geometry) {
  32414. return this._geometry._generatePointsArray();
  32415. }
  32416. return false;
  32417. };
  32418. /**
  32419. * Returns a new Mesh object generated from the current mesh properties.
  32420. * This method must not get confused with createInstance().
  32421. * The parameter `name` is a string, the name given to the new mesh.
  32422. * The optional parameter `newParent` can be any Node object (default `null`).
  32423. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32424. * 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.
  32425. */
  32426. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32427. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32428. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32429. };
  32430. /**
  32431. * Releases resources associated with this mesh.
  32432. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32433. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32434. */
  32435. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32436. var _this = this;
  32437. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32438. this.morphTargetManager = null;
  32439. if (this._geometry) {
  32440. this._geometry.releaseForMesh(this, true);
  32441. }
  32442. // Sources
  32443. var meshes = this.getScene().meshes;
  32444. meshes.forEach(function (abstractMesh) {
  32445. var mesh = abstractMesh;
  32446. if (mesh._source && mesh._source === _this) {
  32447. mesh._source = null;
  32448. }
  32449. });
  32450. this._source = null;
  32451. // Instances
  32452. if (this._instancesBuffer) {
  32453. this._instancesBuffer.dispose();
  32454. this._instancesBuffer = null;
  32455. }
  32456. while (this.instances.length) {
  32457. this.instances[0].dispose();
  32458. }
  32459. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32460. };
  32461. /**
  32462. * Modifies the mesh geometry according to a displacement map.
  32463. * 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.
  32464. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32465. * This method returns nothing.
  32466. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32467. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32468. * 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.
  32469. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32470. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32471. *
  32472. * Returns the Mesh.
  32473. */
  32474. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32475. var _this = this;
  32476. var scene = this.getScene();
  32477. var onload = function (img) {
  32478. // Getting height map data
  32479. var canvas = document.createElement("canvas");
  32480. var context = canvas.getContext("2d");
  32481. var heightMapWidth = img.width;
  32482. var heightMapHeight = img.height;
  32483. canvas.width = heightMapWidth;
  32484. canvas.height = heightMapHeight;
  32485. context.drawImage(img, 0, 0);
  32486. // Create VertexData from map data
  32487. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32488. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32489. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32490. //execute success callback, if set
  32491. if (onSuccess) {
  32492. onSuccess(_this);
  32493. }
  32494. };
  32495. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32496. return this;
  32497. };
  32498. /**
  32499. * Modifies the mesh geometry according to a displacementMap buffer.
  32500. * 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.
  32501. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32502. * This method returns nothing.
  32503. * 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.
  32504. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32505. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32506. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32507. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32508. *
  32509. * Returns the Mesh.
  32510. */
  32511. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32512. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32513. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32514. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32515. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32516. return this;
  32517. }
  32518. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32519. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32520. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32521. var position = BABYLON.Vector3.Zero();
  32522. var normal = BABYLON.Vector3.Zero();
  32523. var uv = BABYLON.Vector2.Zero();
  32524. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32525. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32526. for (var index = 0; index < positions.length; index += 3) {
  32527. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32528. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32529. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32530. // Compute height
  32531. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32532. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32533. var pos = (u + v * heightMapWidth) * 4;
  32534. var r = buffer[pos] / 255.0;
  32535. var g = buffer[pos + 1] / 255.0;
  32536. var b = buffer[pos + 2] / 255.0;
  32537. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32538. normal.normalize();
  32539. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32540. position = position.add(normal);
  32541. position.toArray(positions, index);
  32542. }
  32543. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32544. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32545. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32546. return this;
  32547. };
  32548. /**
  32549. * Modify the mesh to get a flat shading rendering.
  32550. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32551. * This method returns the Mesh.
  32552. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32553. */
  32554. Mesh.prototype.convertToFlatShadedMesh = function () {
  32555. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32556. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32557. var kinds = this.getVerticesDataKinds();
  32558. var vbs = {};
  32559. var data = {};
  32560. var newdata = {};
  32561. var updatableNormals = false;
  32562. var kindIndex;
  32563. var kind;
  32564. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32565. kind = kinds[kindIndex];
  32566. var vertexBuffer = this.getVertexBuffer(kind);
  32567. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32568. updatableNormals = vertexBuffer.isUpdatable();
  32569. kinds.splice(kindIndex, 1);
  32570. kindIndex--;
  32571. continue;
  32572. }
  32573. vbs[kind] = vertexBuffer;
  32574. data[kind] = vbs[kind].getData();
  32575. newdata[kind] = [];
  32576. }
  32577. // Save previous submeshes
  32578. var previousSubmeshes = this.subMeshes.slice(0);
  32579. var indices = this.getIndices();
  32580. var totalIndices = this.getTotalIndices();
  32581. // Generating unique vertices per face
  32582. var index;
  32583. for (index = 0; index < totalIndices; index++) {
  32584. var vertexIndex = indices[index];
  32585. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32586. kind = kinds[kindIndex];
  32587. var stride = vbs[kind].getStrideSize();
  32588. for (var offset = 0; offset < stride; offset++) {
  32589. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32590. }
  32591. }
  32592. }
  32593. // Updating faces & normal
  32594. var normals = [];
  32595. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32596. for (index = 0; index < totalIndices; index += 3) {
  32597. indices[index] = index;
  32598. indices[index + 1] = index + 1;
  32599. indices[index + 2] = index + 2;
  32600. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32601. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32602. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32603. var p1p2 = p1.subtract(p2);
  32604. var p3p2 = p3.subtract(p2);
  32605. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32606. // Store same normals for every vertex
  32607. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32608. normals.push(normal.x);
  32609. normals.push(normal.y);
  32610. normals.push(normal.z);
  32611. }
  32612. }
  32613. this.setIndices(indices);
  32614. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32615. // Updating vertex buffers
  32616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32617. kind = kinds[kindIndex];
  32618. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32619. }
  32620. // Updating submeshes
  32621. this.releaseSubMeshes();
  32622. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32623. var previousOne = previousSubmeshes[submeshIndex];
  32624. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32625. }
  32626. this.synchronizeInstances();
  32627. return this;
  32628. };
  32629. /**
  32630. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32631. * In other words, more vertices, no more indices and a single bigger VBO.
  32632. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32633. * Returns the Mesh.
  32634. */
  32635. Mesh.prototype.convertToUnIndexedMesh = function () {
  32636. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32637. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32638. var kinds = this.getVerticesDataKinds();
  32639. var vbs = {};
  32640. var data = {};
  32641. var newdata = {};
  32642. var kindIndex;
  32643. var kind;
  32644. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32645. kind = kinds[kindIndex];
  32646. var vertexBuffer = this.getVertexBuffer(kind);
  32647. vbs[kind] = vertexBuffer;
  32648. data[kind] = vbs[kind].getData();
  32649. newdata[kind] = [];
  32650. }
  32651. // Save previous submeshes
  32652. var previousSubmeshes = this.subMeshes.slice(0);
  32653. var indices = this.getIndices();
  32654. var totalIndices = this.getTotalIndices();
  32655. // Generating unique vertices per face
  32656. var index;
  32657. for (index = 0; index < totalIndices; index++) {
  32658. var vertexIndex = indices[index];
  32659. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32660. kind = kinds[kindIndex];
  32661. var stride = vbs[kind].getStrideSize();
  32662. for (var offset = 0; offset < stride; offset++) {
  32663. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32664. }
  32665. }
  32666. }
  32667. // Updating indices
  32668. for (index = 0; index < totalIndices; index += 3) {
  32669. indices[index] = index;
  32670. indices[index + 1] = index + 1;
  32671. indices[index + 2] = index + 2;
  32672. }
  32673. this.setIndices(indices);
  32674. // Updating vertex buffers
  32675. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32676. kind = kinds[kindIndex];
  32677. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32678. }
  32679. // Updating submeshes
  32680. this.releaseSubMeshes();
  32681. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32682. var previousOne = previousSubmeshes[submeshIndex];
  32683. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32684. }
  32685. this._unIndexed = true;
  32686. this.synchronizeInstances();
  32687. return this;
  32688. };
  32689. /**
  32690. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32691. * This method returns the Mesh.
  32692. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32693. */
  32694. Mesh.prototype.flipFaces = function (flipNormals) {
  32695. if (flipNormals === void 0) { flipNormals = false; }
  32696. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32697. var i;
  32698. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32699. for (i = 0; i < vertex_data.normals.length; i++) {
  32700. vertex_data.normals[i] *= -1;
  32701. }
  32702. }
  32703. if (vertex_data.indices) {
  32704. var temp;
  32705. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32706. // reassign indices
  32707. temp = vertex_data.indices[i + 1];
  32708. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32709. vertex_data.indices[i + 2] = temp;
  32710. }
  32711. }
  32712. vertex_data.applyToMesh(this);
  32713. return this;
  32714. };
  32715. // Instances
  32716. /**
  32717. * Creates a new InstancedMesh object from the mesh model.
  32718. * An instance shares the same properties and the same material than its model.
  32719. * Only these properties of each instance can then be set individually :
  32720. * - position
  32721. * - rotation
  32722. * - rotationQuaternion
  32723. * - setPivotMatrix
  32724. * - scaling
  32725. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32726. * Warning : this method is not supported for Line mesh and LineSystem
  32727. */
  32728. Mesh.prototype.createInstance = function (name) {
  32729. return new BABYLON.InstancedMesh(name, this);
  32730. };
  32731. /**
  32732. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32733. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32734. * This method returns the Mesh.
  32735. */
  32736. Mesh.prototype.synchronizeInstances = function () {
  32737. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32738. var instance = this.instances[instanceIndex];
  32739. instance._syncSubMeshes();
  32740. }
  32741. return this;
  32742. };
  32743. /**
  32744. * Simplify the mesh according to the given array of settings.
  32745. * Function will return immediately and will simplify async. It returns the Mesh.
  32746. * @param settings a collection of simplification settings.
  32747. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32748. * @param type the type of simplification to run.
  32749. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32750. */
  32751. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32752. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32753. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32754. this.getScene().simplificationQueue.addTask({
  32755. settings: settings,
  32756. parallelProcessing: parallelProcessing,
  32757. mesh: this,
  32758. simplificationType: simplificationType,
  32759. successCallback: successCallback
  32760. });
  32761. return this;
  32762. };
  32763. /**
  32764. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32765. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32766. * This should be used together with the simplification to avoid disappearing triangles.
  32767. * Returns the Mesh.
  32768. * @param successCallback an optional success callback to be called after the optimization finished.
  32769. */
  32770. Mesh.prototype.optimizeIndices = function (successCallback) {
  32771. var _this = this;
  32772. var indices = this.getIndices();
  32773. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32774. if (!positions || !indices) {
  32775. return this;
  32776. }
  32777. var vectorPositions = new Array();
  32778. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32779. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32780. }
  32781. var dupes = new Array();
  32782. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32783. var realPos = vectorPositions.length - 1 - iteration;
  32784. var testedPosition = vectorPositions[realPos];
  32785. for (var j = 0; j < realPos; ++j) {
  32786. var againstPosition = vectorPositions[j];
  32787. if (testedPosition.equals(againstPosition)) {
  32788. dupes[realPos] = j;
  32789. break;
  32790. }
  32791. }
  32792. }, function () {
  32793. for (var i = 0; i < indices.length; ++i) {
  32794. indices[i] = dupes[indices[i]] || indices[i];
  32795. }
  32796. //indices are now reordered
  32797. var originalSubMeshes = _this.subMeshes.slice(0);
  32798. _this.setIndices(indices);
  32799. _this.subMeshes = originalSubMeshes;
  32800. if (successCallback) {
  32801. successCallback(_this);
  32802. }
  32803. });
  32804. return this;
  32805. };
  32806. Mesh.prototype.serialize = function (serializationObject) {
  32807. serializationObject.name = this.name;
  32808. serializationObject.id = this.id;
  32809. serializationObject.type = this.getClassName();
  32810. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32811. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32812. }
  32813. serializationObject.position = this.position.asArray();
  32814. if (this.rotationQuaternion) {
  32815. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32816. }
  32817. else if (this.rotation) {
  32818. serializationObject.rotation = this.rotation.asArray();
  32819. }
  32820. serializationObject.scaling = this.scaling.asArray();
  32821. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32822. serializationObject.isEnabled = this.isEnabled(false);
  32823. serializationObject.isVisible = this.isVisible;
  32824. serializationObject.infiniteDistance = this.infiniteDistance;
  32825. serializationObject.pickable = this.isPickable;
  32826. serializationObject.receiveShadows = this.receiveShadows;
  32827. serializationObject.billboardMode = this.billboardMode;
  32828. serializationObject.visibility = this.visibility;
  32829. serializationObject.checkCollisions = this.checkCollisions;
  32830. serializationObject.isBlocker = this.isBlocker;
  32831. // Parent
  32832. if (this.parent) {
  32833. serializationObject.parentId = this.parent.id;
  32834. }
  32835. // Geometry
  32836. serializationObject.isUnIndexed = this.isUnIndexed;
  32837. var geometry = this._geometry;
  32838. if (geometry) {
  32839. var geometryId = geometry.id;
  32840. serializationObject.geometryId = geometryId;
  32841. // SubMeshes
  32842. serializationObject.subMeshes = [];
  32843. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32844. var subMesh = this.subMeshes[subIndex];
  32845. serializationObject.subMeshes.push({
  32846. materialIndex: subMesh.materialIndex,
  32847. verticesStart: subMesh.verticesStart,
  32848. verticesCount: subMesh.verticesCount,
  32849. indexStart: subMesh.indexStart,
  32850. indexCount: subMesh.indexCount
  32851. });
  32852. }
  32853. }
  32854. // Material
  32855. if (this.material) {
  32856. serializationObject.materialId = this.material.id;
  32857. }
  32858. else {
  32859. this.material = null;
  32860. }
  32861. // Morph targets
  32862. if (this.morphTargetManager) {
  32863. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32864. }
  32865. // Skeleton
  32866. if (this.skeleton) {
  32867. serializationObject.skeletonId = this.skeleton.id;
  32868. }
  32869. // Physics
  32870. //TODO implement correct serialization for physics impostors.
  32871. var impostor = this.getPhysicsImpostor();
  32872. if (impostor) {
  32873. serializationObject.physicsMass = impostor.getParam("mass");
  32874. serializationObject.physicsFriction = impostor.getParam("friction");
  32875. serializationObject.physicsRestitution = impostor.getParam("mass");
  32876. serializationObject.physicsImpostor = impostor.type;
  32877. }
  32878. // Metadata
  32879. if (this.metadata) {
  32880. serializationObject.metadata = this.metadata;
  32881. }
  32882. // Instances
  32883. serializationObject.instances = [];
  32884. for (var index = 0; index < this.instances.length; index++) {
  32885. var instance = this.instances[index];
  32886. var serializationInstance = {
  32887. name: instance.name,
  32888. id: instance.id,
  32889. position: instance.position.asArray(),
  32890. scaling: instance.scaling.asArray()
  32891. };
  32892. if (instance.rotationQuaternion) {
  32893. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32894. }
  32895. else if (instance.rotation) {
  32896. serializationInstance.rotation = instance.rotation.asArray();
  32897. }
  32898. serializationObject.instances.push(serializationInstance);
  32899. // Animations
  32900. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32901. serializationInstance.ranges = instance.serializeAnimationRanges();
  32902. }
  32903. //
  32904. // Animations
  32905. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32906. serializationObject.ranges = this.serializeAnimationRanges();
  32907. // Layer mask
  32908. serializationObject.layerMask = this.layerMask;
  32909. // Alpha
  32910. serializationObject.alphaIndex = this.alphaIndex;
  32911. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32912. // Overlay
  32913. serializationObject.overlayAlpha = this.overlayAlpha;
  32914. serializationObject.overlayColor = this.overlayColor.asArray();
  32915. serializationObject.renderOverlay = this.renderOverlay;
  32916. // Fog
  32917. serializationObject.applyFog = this.applyFog;
  32918. // Action Manager
  32919. if (this.actionManager) {
  32920. serializationObject.actions = this.actionManager.serialize(this.name);
  32921. }
  32922. };
  32923. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32924. if (!this.geometry) {
  32925. return;
  32926. }
  32927. this._markSubMeshesAsAttributesDirty();
  32928. var morphTargetManager = this._morphTargetManager;
  32929. if (morphTargetManager && morphTargetManager.vertexCount) {
  32930. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32931. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32932. this.morphTargetManager = null;
  32933. return;
  32934. }
  32935. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32936. var morphTarget = morphTargetManager.getActiveTarget(index);
  32937. var positions = morphTarget.getPositions();
  32938. if (!positions) {
  32939. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32940. return;
  32941. }
  32942. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32943. var normals = morphTarget.getNormals();
  32944. if (normals) {
  32945. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32946. }
  32947. var tangents = morphTarget.getTangents();
  32948. if (tangents) {
  32949. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32950. }
  32951. }
  32952. }
  32953. else {
  32954. var index = 0;
  32955. // Positions
  32956. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32957. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32958. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32959. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32960. }
  32961. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32962. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32963. }
  32964. index++;
  32965. }
  32966. }
  32967. };
  32968. // Statics
  32969. /**
  32970. * Returns a new Mesh object parsed from the source provided.
  32971. * The parameter `parsedMesh` is the source.
  32972. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32973. */
  32974. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32975. var mesh;
  32976. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32977. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32978. }
  32979. else {
  32980. mesh = new Mesh(parsedMesh.name, scene);
  32981. }
  32982. mesh.id = parsedMesh.id;
  32983. if (BABYLON.Tags) {
  32984. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32985. }
  32986. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32987. if (parsedMesh.metadata !== undefined) {
  32988. mesh.metadata = parsedMesh.metadata;
  32989. }
  32990. if (parsedMesh.rotationQuaternion) {
  32991. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32992. }
  32993. else if (parsedMesh.rotation) {
  32994. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32995. }
  32996. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32997. if (parsedMesh.localMatrix) {
  32998. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32999. }
  33000. else if (parsedMesh.pivotMatrix) {
  33001. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33002. }
  33003. mesh.setEnabled(parsedMesh.isEnabled);
  33004. mesh.isVisible = parsedMesh.isVisible;
  33005. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33006. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33007. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33008. if (parsedMesh.applyFog !== undefined) {
  33009. mesh.applyFog = parsedMesh.applyFog;
  33010. }
  33011. if (parsedMesh.pickable !== undefined) {
  33012. mesh.isPickable = parsedMesh.pickable;
  33013. }
  33014. if (parsedMesh.alphaIndex !== undefined) {
  33015. mesh.alphaIndex = parsedMesh.alphaIndex;
  33016. }
  33017. mesh.receiveShadows = parsedMesh.receiveShadows;
  33018. mesh.billboardMode = parsedMesh.billboardMode;
  33019. if (parsedMesh.visibility !== undefined) {
  33020. mesh.visibility = parsedMesh.visibility;
  33021. }
  33022. mesh.checkCollisions = parsedMesh.checkCollisions;
  33023. if (parsedMesh.isBlocker !== undefined) {
  33024. mesh.isBlocker = parsedMesh.isBlocker;
  33025. }
  33026. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33027. // freezeWorldMatrix
  33028. if (parsedMesh.freezeWorldMatrix) {
  33029. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33030. }
  33031. // Parent
  33032. if (parsedMesh.parentId) {
  33033. mesh._waitingParentId = parsedMesh.parentId;
  33034. }
  33035. // Actions
  33036. if (parsedMesh.actions !== undefined) {
  33037. mesh._waitingActions = parsedMesh.actions;
  33038. }
  33039. // Overlay
  33040. if (parsedMesh.overlayAlpha !== undefined) {
  33041. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33042. }
  33043. if (parsedMesh.overlayColor !== undefined) {
  33044. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33045. }
  33046. if (parsedMesh.renderOverlay !== undefined) {
  33047. mesh.renderOverlay = parsedMesh.renderOverlay;
  33048. }
  33049. // Geometry
  33050. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33051. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33052. if (parsedMesh.delayLoadingFile) {
  33053. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33054. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33055. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33056. if (parsedMesh._binaryInfo) {
  33057. mesh._binaryInfo = parsedMesh._binaryInfo;
  33058. }
  33059. mesh._delayInfo = [];
  33060. if (parsedMesh.hasUVs) {
  33061. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33062. }
  33063. if (parsedMesh.hasUVs2) {
  33064. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33065. }
  33066. if (parsedMesh.hasUVs3) {
  33067. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33068. }
  33069. if (parsedMesh.hasUVs4) {
  33070. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33071. }
  33072. if (parsedMesh.hasUVs5) {
  33073. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33074. }
  33075. if (parsedMesh.hasUVs6) {
  33076. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33077. }
  33078. if (parsedMesh.hasColors) {
  33079. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33080. }
  33081. if (parsedMesh.hasMatricesIndices) {
  33082. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33083. }
  33084. if (parsedMesh.hasMatricesWeights) {
  33085. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33086. }
  33087. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33088. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33089. mesh._checkDelayState();
  33090. }
  33091. }
  33092. else {
  33093. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33094. }
  33095. // Material
  33096. if (parsedMesh.materialId) {
  33097. mesh.setMaterialByID(parsedMesh.materialId);
  33098. }
  33099. else {
  33100. mesh.material = null;
  33101. }
  33102. // Morph targets
  33103. if (parsedMesh.morphTargetManagerId > -1) {
  33104. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33105. }
  33106. // Skeleton
  33107. if (parsedMesh.skeletonId > -1) {
  33108. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33109. if (parsedMesh.numBoneInfluencers) {
  33110. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33111. }
  33112. }
  33113. // Animations
  33114. if (parsedMesh.animations) {
  33115. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33116. var parsedAnimation = parsedMesh.animations[animationIndex];
  33117. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33118. }
  33119. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33120. }
  33121. if (parsedMesh.autoAnimate) {
  33122. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33123. }
  33124. // Layer Mask
  33125. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33126. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33127. }
  33128. else {
  33129. mesh.layerMask = 0x0FFFFFFF;
  33130. }
  33131. // Physics
  33132. if (parsedMesh.physicsImpostor) {
  33133. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33134. mass: parsedMesh.physicsMass,
  33135. friction: parsedMesh.physicsFriction,
  33136. restitution: parsedMesh.physicsRestitution
  33137. }, scene);
  33138. }
  33139. // Instances
  33140. if (parsedMesh.instances) {
  33141. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33142. var parsedInstance = parsedMesh.instances[index];
  33143. var instance = mesh.createInstance(parsedInstance.name);
  33144. if (parsedInstance.id) {
  33145. instance.id = parsedInstance.id;
  33146. }
  33147. if (BABYLON.Tags) {
  33148. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33149. }
  33150. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33151. if (parsedInstance.parentId) {
  33152. instance._waitingParentId = parsedInstance.parentId;
  33153. }
  33154. if (parsedInstance.rotationQuaternion) {
  33155. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33156. }
  33157. else if (parsedInstance.rotation) {
  33158. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33159. }
  33160. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33161. instance.checkCollisions = mesh.checkCollisions;
  33162. if (parsedMesh.animations) {
  33163. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33164. parsedAnimation = parsedMesh.animations[animationIndex];
  33165. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33166. }
  33167. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33168. if (parsedMesh.autoAnimate) {
  33169. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33170. }
  33171. }
  33172. }
  33173. }
  33174. return mesh;
  33175. };
  33176. /**
  33177. * Creates a ribbon mesh.
  33178. * Please consider using the same method from the MeshBuilder class instead.
  33179. * 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.
  33180. *
  33181. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33182. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33183. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33184. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33185. * 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.
  33186. * 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.
  33187. * 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
  33188. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33189. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33191. */
  33192. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33193. if (closeArray === void 0) { closeArray = false; }
  33194. if (updatable === void 0) { updatable = false; }
  33195. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33196. pathArray: pathArray,
  33197. closeArray: closeArray,
  33198. closePath: closePath,
  33199. offset: offset,
  33200. updatable: updatable,
  33201. sideOrientation: sideOrientation,
  33202. instance: instance
  33203. }, scene);
  33204. };
  33205. /**
  33206. * Creates a plane polygonal mesh. By default, this is a disc.
  33207. * Please consider using the same method from the MeshBuilder class instead.
  33208. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33209. * 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.
  33210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33211. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33213. */
  33214. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33215. if (scene === void 0) { scene = null; }
  33216. var options = {
  33217. radius: radius,
  33218. tessellation: tessellation,
  33219. sideOrientation: sideOrientation,
  33220. updatable: updatable
  33221. };
  33222. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33223. };
  33224. /**
  33225. * Creates a box mesh.
  33226. * Please consider using the same method from the MeshBuilder class instead.
  33227. * The parameter `size` sets the size (float) of each box side (default 1).
  33228. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33229. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33231. */
  33232. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33233. if (scene === void 0) { scene = null; }
  33234. var options = {
  33235. size: size,
  33236. sideOrientation: sideOrientation,
  33237. updatable: updatable
  33238. };
  33239. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33240. };
  33241. /**
  33242. * Creates a sphere mesh.
  33243. * Please consider using the same method from the MeshBuilder class instead.
  33244. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33245. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33247. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33249. */
  33250. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33251. var options = {
  33252. segments: segments,
  33253. diameterX: diameter,
  33254. diameterY: diameter,
  33255. diameterZ: diameter,
  33256. sideOrientation: sideOrientation,
  33257. updatable: updatable
  33258. };
  33259. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33260. };
  33261. /**
  33262. * Creates a cylinder or a cone mesh.
  33263. * Please consider using the same method from the MeshBuilder class instead.
  33264. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33265. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33266. * 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.
  33267. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33268. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33270. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33272. */
  33273. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33274. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33275. if (scene !== undefined) {
  33276. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33277. updatable = scene;
  33278. }
  33279. scene = subdivisions;
  33280. subdivisions = 1;
  33281. }
  33282. var options = {
  33283. height: height,
  33284. diameterTop: diameterTop,
  33285. diameterBottom: diameterBottom,
  33286. tessellation: tessellation,
  33287. subdivisions: subdivisions,
  33288. sideOrientation: sideOrientation,
  33289. updatable: updatable
  33290. };
  33291. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33292. };
  33293. // Torus (Code from SharpDX.org)
  33294. /**
  33295. * Creates a torus mesh.
  33296. * Please consider using the same method from the MeshBuilder class instead.
  33297. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33298. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33299. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33301. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33303. */
  33304. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33305. var options = {
  33306. diameter: diameter,
  33307. thickness: thickness,
  33308. tessellation: tessellation,
  33309. sideOrientation: sideOrientation,
  33310. updatable: updatable
  33311. };
  33312. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33313. };
  33314. /**
  33315. * Creates a torus knot mesh.
  33316. * Please consider using the same method from the MeshBuilder class instead.
  33317. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33318. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33319. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33320. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33322. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33324. */
  33325. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33326. var options = {
  33327. radius: radius,
  33328. tube: tube,
  33329. radialSegments: radialSegments,
  33330. tubularSegments: tubularSegments,
  33331. p: p,
  33332. q: q,
  33333. sideOrientation: sideOrientation,
  33334. updatable: updatable
  33335. };
  33336. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33337. };
  33338. /**
  33339. * Creates a line mesh.
  33340. * Please consider using the same method from the MeshBuilder class instead.
  33341. * 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.
  33342. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33343. * The parameter `points` is an array successive Vector3.
  33344. * 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
  33345. * When updating an instance, remember that only point positions can change, not the number of points.
  33346. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33347. */
  33348. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33349. if (scene === void 0) { scene = null; }
  33350. if (updatable === void 0) { updatable = false; }
  33351. if (instance === void 0) { instance = null; }
  33352. var options = {
  33353. points: points,
  33354. updatable: updatable,
  33355. instance: instance
  33356. };
  33357. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33358. };
  33359. /**
  33360. * Creates a dashed line mesh.
  33361. * Please consider using the same method from the MeshBuilder class instead.
  33362. * 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.
  33363. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33364. * The parameter `points` is an array successive Vector3.
  33365. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33366. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33367. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33368. * 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
  33369. * When updating an instance, remember that only point positions can change, not the number of points.
  33370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33371. */
  33372. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33373. if (scene === void 0) { scene = null; }
  33374. var options = {
  33375. points: points,
  33376. dashSize: dashSize,
  33377. gapSize: gapSize,
  33378. dashNb: dashNb,
  33379. updatable: updatable,
  33380. instance: instance
  33381. };
  33382. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33383. };
  33384. /**
  33385. * Creates a polygon mesh.
  33386. * Please consider using the same method from the MeshBuilder class instead.
  33387. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33388. * 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.
  33389. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33391. * Remember you can only change the shape positions, not their number when updating a polygon.
  33392. */
  33393. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33394. var options = {
  33395. shape: shape,
  33396. holes: holes,
  33397. updatable: updatable,
  33398. sideOrientation: sideOrientation
  33399. };
  33400. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33401. };
  33402. /**
  33403. * Creates an extruded polygon mesh, with depth in the Y direction.
  33404. * Please consider using the same method from the MeshBuilder class instead.
  33405. */
  33406. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33407. var options = {
  33408. shape: shape,
  33409. holes: holes,
  33410. depth: depth,
  33411. updatable: updatable,
  33412. sideOrientation: sideOrientation
  33413. };
  33414. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33415. };
  33416. /**
  33417. * Creates an extruded shape mesh.
  33418. * 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.
  33419. * Please consider using the same method from the MeshBuilder class instead.
  33420. *
  33421. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33422. * 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
  33423. * extruded along the Z axis.
  33424. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33425. * 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.
  33426. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33427. * 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
  33428. * 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
  33429. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33430. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33431. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33433. */
  33434. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33435. if (scene === void 0) { scene = null; }
  33436. var options = {
  33437. shape: shape,
  33438. path: path,
  33439. scale: scale,
  33440. rotation: rotation,
  33441. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33442. sideOrientation: sideOrientation,
  33443. instance: instance,
  33444. updatable: updatable
  33445. };
  33446. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33447. };
  33448. /**
  33449. * Creates an custom extruded shape mesh.
  33450. * 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.
  33451. * Please consider using the same method from the MeshBuilder class instead.
  33452. *
  33453. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33454. * 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
  33455. * extruded along the Z axis.
  33456. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33457. * 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
  33458. * and the distance of this point from the begining of the path :
  33459. * ```javascript
  33460. * var rotationFunction = function(i, distance) {
  33461. * // do things
  33462. * return rotationValue; }
  33463. * ```
  33464. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33465. * 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
  33466. * and the distance of this point from the begining of the path :
  33467. * ```javascript
  33468. * var scaleFunction = function(i, distance) {
  33469. * // do things
  33470. * return scaleValue;}
  33471. * ```
  33472. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33473. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33474. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33475. * 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
  33476. * 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
  33477. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33478. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33479. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33481. */
  33482. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33483. var options = {
  33484. shape: shape,
  33485. path: path,
  33486. scaleFunction: scaleFunction,
  33487. rotationFunction: rotationFunction,
  33488. ribbonCloseArray: ribbonCloseArray,
  33489. ribbonClosePath: ribbonClosePath,
  33490. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33491. sideOrientation: sideOrientation,
  33492. instance: instance,
  33493. updatable: updatable
  33494. };
  33495. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33496. };
  33497. /**
  33498. * Creates lathe mesh.
  33499. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33500. * Please consider using the same method from the MeshBuilder class instead.
  33501. * 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
  33502. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33503. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33504. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33505. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33506. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33508. */
  33509. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33510. var options = {
  33511. shape: shape,
  33512. radius: radius,
  33513. tessellation: tessellation,
  33514. sideOrientation: sideOrientation,
  33515. updatable: updatable
  33516. };
  33517. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33518. };
  33519. /**
  33520. * Creates a plane mesh.
  33521. * Please consider using the same method from the MeshBuilder class instead.
  33522. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33523. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33524. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33526. */
  33527. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33528. var options = {
  33529. size: size,
  33530. width: size,
  33531. height: size,
  33532. sideOrientation: sideOrientation,
  33533. updatable: updatable
  33534. };
  33535. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33536. };
  33537. /**
  33538. * Creates a ground mesh.
  33539. * Please consider using the same method from the MeshBuilder class instead.
  33540. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33541. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33543. */
  33544. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33545. var options = {
  33546. width: width,
  33547. height: height,
  33548. subdivisions: subdivisions,
  33549. updatable: updatable
  33550. };
  33551. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33552. };
  33553. /**
  33554. * Creates a tiled ground mesh.
  33555. * Please consider using the same method from the MeshBuilder class instead.
  33556. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33557. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33558. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33559. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33560. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33561. * numbers of subdivisions on the ground width and height of each tile.
  33562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33563. */
  33564. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33565. var options = {
  33566. xmin: xmin,
  33567. zmin: zmin,
  33568. xmax: xmax,
  33569. zmax: zmax,
  33570. subdivisions: subdivisions,
  33571. precision: precision,
  33572. updatable: updatable
  33573. };
  33574. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33575. };
  33576. /**
  33577. * Creates a ground mesh from a height map.
  33578. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33579. * Please consider using the same method from the MeshBuilder class instead.
  33580. * The parameter `url` sets the URL of the height map image resource.
  33581. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33582. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33583. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33584. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33585. * 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).
  33586. * This function is passed the newly built mesh :
  33587. * ```javascript
  33588. * function(mesh) { // do things
  33589. * return; }
  33590. * ```
  33591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33592. */
  33593. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33594. var options = {
  33595. width: width,
  33596. height: height,
  33597. subdivisions: subdivisions,
  33598. minHeight: minHeight,
  33599. maxHeight: maxHeight,
  33600. updatable: updatable,
  33601. onReady: onReady
  33602. };
  33603. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33604. };
  33605. /**
  33606. * Creates a tube mesh.
  33607. * 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.
  33608. * Please consider using the same method from the MeshBuilder class instead.
  33609. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33610. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33611. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33612. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33613. * 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.
  33614. * It must return a radius value (positive float) :
  33615. * ```javascript
  33616. * var radiusFunction = function(i, distance) {
  33617. * // do things
  33618. * return radius; }
  33619. * ```
  33620. * 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
  33621. * 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
  33622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33623. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33625. */
  33626. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33627. var options = {
  33628. path: path,
  33629. radius: radius,
  33630. tessellation: tessellation,
  33631. radiusFunction: radiusFunction,
  33632. arc: 1,
  33633. cap: cap,
  33634. updatable: updatable,
  33635. sideOrientation: sideOrientation,
  33636. instance: instance
  33637. };
  33638. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33639. };
  33640. /**
  33641. * Creates a polyhedron mesh.
  33642. * Please consider using the same method from the MeshBuilder class instead.
  33643. * 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
  33644. * to choose the wanted type.
  33645. * The parameter `size` (positive float, default 1) sets the polygon size.
  33646. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33647. * 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`.
  33648. * 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
  33649. * 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)`).
  33650. * 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
  33651. * 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.
  33652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33653. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33655. */
  33656. Mesh.CreatePolyhedron = function (name, options, scene) {
  33657. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33658. };
  33659. /**
  33660. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33661. * Please consider using the same method from the MeshBuilder class instead.
  33662. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33663. * 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`).
  33664. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33665. * 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.
  33666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33667. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33669. */
  33670. Mesh.CreateIcoSphere = function (name, options, scene) {
  33671. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33672. };
  33673. /**
  33674. * Creates a decal mesh.
  33675. * Please consider using the same method from the MeshBuilder class instead.
  33676. * 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.
  33677. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33678. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33679. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33680. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33681. */
  33682. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33683. var options = {
  33684. position: position,
  33685. normal: normal,
  33686. size: size,
  33687. angle: angle
  33688. };
  33689. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33690. };
  33691. // Skeletons
  33692. /**
  33693. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33694. */
  33695. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33696. if (!this._sourcePositions) {
  33697. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33698. if (!source) {
  33699. return this._sourcePositions;
  33700. }
  33701. this._sourcePositions = new Float32Array(source);
  33702. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33703. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33704. }
  33705. }
  33706. return this._sourcePositions;
  33707. };
  33708. /**
  33709. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33710. */
  33711. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33712. if (!this._sourceNormals) {
  33713. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33714. if (!source) {
  33715. return this._sourceNormals;
  33716. }
  33717. this._sourceNormals = new Float32Array(source);
  33718. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33719. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33720. }
  33721. }
  33722. return this._sourceNormals;
  33723. };
  33724. /**
  33725. * Updates the vertex buffer by applying transformation from the bones.
  33726. * Returns the Mesh.
  33727. *
  33728. * @param {skeleton} skeleton to apply
  33729. */
  33730. Mesh.prototype.applySkeleton = function (skeleton) {
  33731. if (!this.geometry) {
  33732. return this;
  33733. }
  33734. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33735. return this;
  33736. }
  33737. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33738. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33739. return this;
  33740. }
  33741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33742. return this;
  33743. }
  33744. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33745. return this;
  33746. }
  33747. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33748. return this;
  33749. }
  33750. if (!this._sourcePositions) {
  33751. var submeshes = this.subMeshes.slice();
  33752. this.setPositionsForCPUSkinning();
  33753. this.subMeshes = submeshes;
  33754. }
  33755. if (!this._sourceNormals) {
  33756. this.setNormalsForCPUSkinning();
  33757. }
  33758. // positionsData checks for not being Float32Array will only pass at most once
  33759. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33760. if (!positionsData) {
  33761. return this;
  33762. }
  33763. if (!(positionsData instanceof Float32Array)) {
  33764. positionsData = new Float32Array(positionsData);
  33765. }
  33766. // normalsData checks for not being Float32Array will only pass at most once
  33767. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33768. if (!normalsData) {
  33769. return this;
  33770. }
  33771. if (!(normalsData instanceof Float32Array)) {
  33772. normalsData = new Float32Array(normalsData);
  33773. }
  33774. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33775. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33776. if (!matricesWeightsData || !matricesIndicesData) {
  33777. return this;
  33778. }
  33779. var needExtras = this.numBoneInfluencers > 4;
  33780. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33781. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33782. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33783. var tempVector3 = BABYLON.Vector3.Zero();
  33784. var finalMatrix = new BABYLON.Matrix();
  33785. var tempMatrix = new BABYLON.Matrix();
  33786. var matWeightIdx = 0;
  33787. var inf;
  33788. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33789. var weight;
  33790. for (inf = 0; inf < 4; inf++) {
  33791. weight = matricesWeightsData[matWeightIdx + inf];
  33792. if (weight > 0) {
  33793. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33794. finalMatrix.addToSelf(tempMatrix);
  33795. }
  33796. }
  33797. if (needExtras) {
  33798. for (inf = 0; inf < 4; inf++) {
  33799. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33800. if (weight > 0) {
  33801. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33802. finalMatrix.addToSelf(tempMatrix);
  33803. }
  33804. }
  33805. }
  33806. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33807. tempVector3.toArray(positionsData, index);
  33808. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33809. tempVector3.toArray(normalsData, index);
  33810. finalMatrix.reset();
  33811. }
  33812. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33813. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33814. return this;
  33815. };
  33816. // Tools
  33817. /**
  33818. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33819. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33820. */
  33821. Mesh.MinMax = function (meshes) {
  33822. var minVector = null;
  33823. var maxVector = null;
  33824. meshes.forEach(function (mesh, index, array) {
  33825. var boundingInfo = mesh.getBoundingInfo();
  33826. var boundingBox = boundingInfo.boundingBox;
  33827. if (!minVector || !maxVector) {
  33828. minVector = boundingBox.minimumWorld;
  33829. maxVector = boundingBox.maximumWorld;
  33830. }
  33831. else {
  33832. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33833. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33834. }
  33835. });
  33836. if (!minVector || !maxVector) {
  33837. return {
  33838. min: BABYLON.Vector3.Zero(),
  33839. max: BABYLON.Vector3.Zero()
  33840. };
  33841. }
  33842. return {
  33843. min: minVector,
  33844. max: maxVector
  33845. };
  33846. };
  33847. /**
  33848. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33849. */
  33850. Mesh.Center = function (meshesOrMinMaxVector) {
  33851. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33852. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33853. };
  33854. /**
  33855. * Merge the array of meshes into a single mesh for performance reasons.
  33856. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33857. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33858. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33859. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33860. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33861. */
  33862. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33863. if (disposeSource === void 0) { disposeSource = true; }
  33864. var index;
  33865. if (!allow32BitsIndices) {
  33866. var totalVertices = 0;
  33867. // Counting vertices
  33868. for (index = 0; index < meshes.length; index++) {
  33869. if (meshes[index]) {
  33870. totalVertices += meshes[index].getTotalVertices();
  33871. if (totalVertices > 65536) {
  33872. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33873. return null;
  33874. }
  33875. }
  33876. }
  33877. }
  33878. // Merge
  33879. var vertexData = null;
  33880. var otherVertexData;
  33881. var indiceArray = new Array();
  33882. var source = null;
  33883. for (index = 0; index < meshes.length; index++) {
  33884. if (meshes[index]) {
  33885. meshes[index].computeWorldMatrix(true);
  33886. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33887. otherVertexData.transform(meshes[index].getWorldMatrix());
  33888. if (vertexData) {
  33889. vertexData.merge(otherVertexData);
  33890. }
  33891. else {
  33892. vertexData = otherVertexData;
  33893. source = meshes[index];
  33894. }
  33895. if (subdivideWithSubMeshes) {
  33896. indiceArray.push(meshes[index].getTotalIndices());
  33897. }
  33898. }
  33899. }
  33900. source = source;
  33901. if (!meshSubclass) {
  33902. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33903. }
  33904. vertexData.applyToMesh(meshSubclass);
  33905. // Setting properties
  33906. meshSubclass.material = source.material;
  33907. meshSubclass.checkCollisions = source.checkCollisions;
  33908. // Cleaning
  33909. if (disposeSource) {
  33910. for (index = 0; index < meshes.length; index++) {
  33911. if (meshes[index]) {
  33912. meshes[index].dispose();
  33913. }
  33914. }
  33915. }
  33916. // Subdivide
  33917. if (subdivideWithSubMeshes) {
  33918. //-- removal of global submesh
  33919. meshSubclass.releaseSubMeshes();
  33920. index = 0;
  33921. var offset = 0;
  33922. //-- apply subdivision according to index table
  33923. while (index < indiceArray.length) {
  33924. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33925. offset += indiceArray[index];
  33926. index++;
  33927. }
  33928. }
  33929. return meshSubclass;
  33930. };
  33931. // Consts
  33932. Mesh._FRONTSIDE = 0;
  33933. Mesh._BACKSIDE = 1;
  33934. Mesh._DOUBLESIDE = 2;
  33935. Mesh._DEFAULTSIDE = 0;
  33936. Mesh._NO_CAP = 0;
  33937. Mesh._CAP_START = 1;
  33938. Mesh._CAP_END = 2;
  33939. Mesh._CAP_ALL = 3;
  33940. return Mesh;
  33941. }(BABYLON.AbstractMesh));
  33942. BABYLON.Mesh = Mesh;
  33943. })(BABYLON || (BABYLON = {}));
  33944. //# sourceMappingURL=babylon.mesh.js.map
  33945. var BABYLON;
  33946. (function (BABYLON) {
  33947. var BaseSubMesh = /** @class */ (function () {
  33948. function BaseSubMesh() {
  33949. }
  33950. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33951. get: function () {
  33952. return this._materialEffect;
  33953. },
  33954. enumerable: true,
  33955. configurable: true
  33956. });
  33957. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33958. if (defines === void 0) { defines = null; }
  33959. if (this._materialEffect === effect) {
  33960. if (!effect) {
  33961. this._materialDefines = null;
  33962. }
  33963. return;
  33964. }
  33965. this._materialDefines = defines;
  33966. this._materialEffect = effect;
  33967. };
  33968. return BaseSubMesh;
  33969. }());
  33970. BABYLON.BaseSubMesh = BaseSubMesh;
  33971. var SubMesh = /** @class */ (function (_super) {
  33972. __extends(SubMesh, _super);
  33973. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33974. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33975. var _this = _super.call(this) || this;
  33976. _this.materialIndex = materialIndex;
  33977. _this.verticesStart = verticesStart;
  33978. _this.verticesCount = verticesCount;
  33979. _this.indexStart = indexStart;
  33980. _this.indexCount = indexCount;
  33981. _this._renderId = 0;
  33982. _this._mesh = mesh;
  33983. _this._renderingMesh = renderingMesh || mesh;
  33984. mesh.subMeshes.push(_this);
  33985. _this._trianglePlanes = [];
  33986. _this._id = mesh.subMeshes.length - 1;
  33987. if (createBoundingBox) {
  33988. _this.refreshBoundingInfo();
  33989. mesh.computeWorldMatrix(true);
  33990. }
  33991. return _this;
  33992. }
  33993. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33994. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33995. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33996. };
  33997. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33998. get: function () {
  33999. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34000. },
  34001. enumerable: true,
  34002. configurable: true
  34003. });
  34004. /**
  34005. * Returns the submesh BoudingInfo object.
  34006. */
  34007. SubMesh.prototype.getBoundingInfo = function () {
  34008. if (this.IsGlobal) {
  34009. return this._mesh.getBoundingInfo();
  34010. }
  34011. return this._boundingInfo;
  34012. };
  34013. /**
  34014. * Sets the submesh BoundingInfo.
  34015. * Return the SubMesh.
  34016. */
  34017. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34018. this._boundingInfo = boundingInfo;
  34019. return this;
  34020. };
  34021. /**
  34022. * Returns the mesh of the current submesh.
  34023. */
  34024. SubMesh.prototype.getMesh = function () {
  34025. return this._mesh;
  34026. };
  34027. /**
  34028. * Returns the rendering mesh of the submesh.
  34029. */
  34030. SubMesh.prototype.getRenderingMesh = function () {
  34031. return this._renderingMesh;
  34032. };
  34033. /**
  34034. * Returns the submesh material.
  34035. */
  34036. SubMesh.prototype.getMaterial = function () {
  34037. var rootMaterial = this._renderingMesh.material;
  34038. if (rootMaterial === null || rootMaterial === undefined) {
  34039. return this._mesh.getScene().defaultMaterial;
  34040. }
  34041. else if (rootMaterial.getSubMaterial) {
  34042. var multiMaterial = rootMaterial;
  34043. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34044. if (this._currentMaterial !== effectiveMaterial) {
  34045. this._currentMaterial = effectiveMaterial;
  34046. this._materialDefines = null;
  34047. }
  34048. return effectiveMaterial;
  34049. }
  34050. return rootMaterial;
  34051. };
  34052. // Methods
  34053. /**
  34054. * Sets a new updated BoundingInfo object to the submesh.
  34055. * Returns the SubMesh.
  34056. */
  34057. SubMesh.prototype.refreshBoundingInfo = function () {
  34058. this._lastColliderWorldVertices = null;
  34059. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34060. return this;
  34061. }
  34062. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34063. if (!data) {
  34064. this._boundingInfo = this._mesh.getBoundingInfo();
  34065. return this;
  34066. }
  34067. var indices = this._renderingMesh.getIndices();
  34068. var extend;
  34069. //is this the only submesh?
  34070. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34071. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34072. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34073. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34074. }
  34075. else {
  34076. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34077. }
  34078. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34079. return this;
  34080. };
  34081. SubMesh.prototype._checkCollision = function (collider) {
  34082. var boundingInfo = this.getBoundingInfo();
  34083. return boundingInfo._checkCollision(collider);
  34084. };
  34085. /**
  34086. * Updates the submesh BoundingInfo.
  34087. * Returns the Submesh.
  34088. */
  34089. SubMesh.prototype.updateBoundingInfo = function (world) {
  34090. var boundingInfo = this.getBoundingInfo();
  34091. if (!boundingInfo) {
  34092. this.refreshBoundingInfo();
  34093. boundingInfo = this.getBoundingInfo();
  34094. }
  34095. boundingInfo.update(world);
  34096. return this;
  34097. };
  34098. /**
  34099. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34100. * Boolean returned.
  34101. */
  34102. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34103. var boundingInfo = this.getBoundingInfo();
  34104. if (!boundingInfo) {
  34105. return false;
  34106. }
  34107. return boundingInfo.isInFrustum(frustumPlanes);
  34108. };
  34109. /**
  34110. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34111. * Boolean returned.
  34112. */
  34113. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34114. var boundingInfo = this.getBoundingInfo();
  34115. if (!boundingInfo) {
  34116. return false;
  34117. }
  34118. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34119. };
  34120. /**
  34121. * Renders the submesh.
  34122. * Returns it.
  34123. */
  34124. SubMesh.prototype.render = function (enableAlphaMode) {
  34125. this._renderingMesh.render(this, enableAlphaMode);
  34126. return this;
  34127. };
  34128. /**
  34129. * Returns a new Index Buffer.
  34130. * Type returned : WebGLBuffer.
  34131. */
  34132. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34133. if (!this._linesIndexBuffer) {
  34134. var linesIndices = [];
  34135. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34136. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34137. }
  34138. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34139. this.linesIndexCount = linesIndices.length;
  34140. }
  34141. return this._linesIndexBuffer;
  34142. };
  34143. /**
  34144. * True is the passed Ray intersects the submesh bounding box.
  34145. * Boolean returned.
  34146. */
  34147. SubMesh.prototype.canIntersects = function (ray) {
  34148. var boundingInfo = this.getBoundingInfo();
  34149. if (!boundingInfo) {
  34150. return false;
  34151. }
  34152. return ray.intersectsBox(boundingInfo.boundingBox);
  34153. };
  34154. /**
  34155. * Returns an object IntersectionInfo.
  34156. */
  34157. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34158. var intersectInfo = null;
  34159. var material = this.getMaterial();
  34160. if (!material) {
  34161. return null;
  34162. }
  34163. switch (material.fillMode) {
  34164. case BABYLON.Material.PointListDrawMode:
  34165. case BABYLON.Material.LineListDrawMode:
  34166. case BABYLON.Material.LineLoopDrawMode:
  34167. case BABYLON.Material.LineStripDrawMode:
  34168. case BABYLON.Material.TriangleFanDrawMode:
  34169. case BABYLON.Material.TriangleStripDrawMode:
  34170. return null;
  34171. }
  34172. // LineMesh first as it's also a Mesh...
  34173. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34174. var lineMesh = this._mesh;
  34175. // Line test
  34176. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34177. var p0 = positions[indices[index]];
  34178. var p1 = positions[indices[index + 1]];
  34179. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34180. if (length < 0) {
  34181. continue;
  34182. }
  34183. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34184. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34185. if (fastCheck) {
  34186. break;
  34187. }
  34188. }
  34189. }
  34190. }
  34191. else {
  34192. // Triangles test
  34193. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34194. var p0 = positions[indices[index]];
  34195. var p1 = positions[indices[index + 1]];
  34196. var p2 = positions[indices[index + 2]];
  34197. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34198. if (currentIntersectInfo) {
  34199. if (currentIntersectInfo.distance < 0) {
  34200. continue;
  34201. }
  34202. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34203. intersectInfo = currentIntersectInfo;
  34204. intersectInfo.faceId = index / 3;
  34205. if (fastCheck) {
  34206. break;
  34207. }
  34208. }
  34209. }
  34210. }
  34211. }
  34212. return intersectInfo;
  34213. };
  34214. SubMesh.prototype._rebuild = function () {
  34215. if (this._linesIndexBuffer) {
  34216. this._linesIndexBuffer = null;
  34217. }
  34218. };
  34219. // Clone
  34220. /**
  34221. * Creates a new Submesh from the passed Mesh.
  34222. */
  34223. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34224. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34225. if (!this.IsGlobal) {
  34226. var boundingInfo = this.getBoundingInfo();
  34227. if (!boundingInfo) {
  34228. return result;
  34229. }
  34230. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34231. }
  34232. return result;
  34233. };
  34234. // Dispose
  34235. /**
  34236. * Disposes the Submesh.
  34237. * Returns nothing.
  34238. */
  34239. SubMesh.prototype.dispose = function () {
  34240. if (this._linesIndexBuffer) {
  34241. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34242. this._linesIndexBuffer = null;
  34243. }
  34244. // Remove from mesh
  34245. var index = this._mesh.subMeshes.indexOf(this);
  34246. this._mesh.subMeshes.splice(index, 1);
  34247. };
  34248. // Statics
  34249. /**
  34250. * Creates a new Submesh from the passed parameters :
  34251. * - materialIndex (integer) : the index of the main mesh material.
  34252. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34253. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34254. * - mesh (Mesh) : the main mesh to create the submesh from.
  34255. * - renderingMesh (optional Mesh) : rendering mesh.
  34256. */
  34257. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34258. var minVertexIndex = Number.MAX_VALUE;
  34259. var maxVertexIndex = -Number.MAX_VALUE;
  34260. renderingMesh = (renderingMesh || mesh);
  34261. var indices = renderingMesh.getIndices();
  34262. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34263. var vertexIndex = indices[index];
  34264. if (vertexIndex < minVertexIndex)
  34265. minVertexIndex = vertexIndex;
  34266. if (vertexIndex > maxVertexIndex)
  34267. maxVertexIndex = vertexIndex;
  34268. }
  34269. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34270. };
  34271. return SubMesh;
  34272. }(BaseSubMesh));
  34273. BABYLON.SubMesh = SubMesh;
  34274. })(BABYLON || (BABYLON = {}));
  34275. //# sourceMappingURL=babylon.subMesh.js.map
  34276. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34277. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34278. s = arguments[i];
  34279. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34280. t[p] = s[p];
  34281. }
  34282. return t;
  34283. };
  34284. var BABYLON;
  34285. (function (BABYLON) {
  34286. /**
  34287. * Manages the defines for the Material
  34288. */
  34289. var MaterialDefines = /** @class */ (function () {
  34290. function MaterialDefines() {
  34291. this._isDirty = true;
  34292. /** @hidden */
  34293. this._areLightsDirty = true;
  34294. /** @hidden */
  34295. this._areAttributesDirty = true;
  34296. /** @hidden */
  34297. this._areTexturesDirty = true;
  34298. /** @hidden */
  34299. this._areFresnelDirty = true;
  34300. /** @hidden */
  34301. this._areMiscDirty = true;
  34302. /** @hidden */
  34303. this._areImageProcessingDirty = true;
  34304. /** @hidden */
  34305. this._normals = false;
  34306. /** @hidden */
  34307. this._uvs = false;
  34308. /** @hidden */
  34309. this._needNormals = false;
  34310. /** @hidden */
  34311. this._needUVs = false;
  34312. }
  34313. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34314. /**
  34315. * Specifies if the material needs to be re-calculated
  34316. */
  34317. get: function () {
  34318. return this._isDirty;
  34319. },
  34320. enumerable: true,
  34321. configurable: true
  34322. });
  34323. /**
  34324. * Marks the material to indicate that it has been re-calculated
  34325. */
  34326. MaterialDefines.prototype.markAsProcessed = function () {
  34327. this._isDirty = false;
  34328. this._areAttributesDirty = false;
  34329. this._areTexturesDirty = false;
  34330. this._areFresnelDirty = false;
  34331. this._areLightsDirty = false;
  34332. this._areMiscDirty = false;
  34333. this._areImageProcessingDirty = false;
  34334. };
  34335. /**
  34336. * Marks the material to indicate that it needs to be re-calculated
  34337. */
  34338. MaterialDefines.prototype.markAsUnprocessed = function () {
  34339. this._isDirty = true;
  34340. };
  34341. /**
  34342. * Marks the material to indicate all of its defines need to be re-calculated
  34343. */
  34344. MaterialDefines.prototype.markAllAsDirty = function () {
  34345. this._areTexturesDirty = true;
  34346. this._areAttributesDirty = true;
  34347. this._areLightsDirty = true;
  34348. this._areFresnelDirty = true;
  34349. this._areMiscDirty = true;
  34350. this._areImageProcessingDirty = true;
  34351. this._isDirty = true;
  34352. };
  34353. /**
  34354. * Marks the material to indicate that image processing needs to be re-calculated
  34355. */
  34356. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34357. this._areImageProcessingDirty = true;
  34358. this._isDirty = true;
  34359. };
  34360. /**
  34361. * Marks the material to indicate the lights need to be re-calculated
  34362. */
  34363. MaterialDefines.prototype.markAsLightDirty = function () {
  34364. this._areLightsDirty = true;
  34365. this._isDirty = true;
  34366. };
  34367. /**
  34368. * Marks the attribute state as changed
  34369. */
  34370. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34371. this._areAttributesDirty = true;
  34372. this._isDirty = true;
  34373. };
  34374. /**
  34375. * Marks the texture state as changed
  34376. */
  34377. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34378. this._areTexturesDirty = true;
  34379. this._isDirty = true;
  34380. };
  34381. /**
  34382. * Marks the fresnel state as changed
  34383. */
  34384. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34385. this._areFresnelDirty = true;
  34386. this._isDirty = true;
  34387. };
  34388. /**
  34389. * Marks the misc state as changed
  34390. */
  34391. MaterialDefines.prototype.markAsMiscDirty = function () {
  34392. this._areMiscDirty = true;
  34393. this._isDirty = true;
  34394. };
  34395. /**
  34396. * Rebuilds the material defines
  34397. */
  34398. MaterialDefines.prototype.rebuild = function () {
  34399. if (this._keys) {
  34400. delete this._keys;
  34401. }
  34402. this._keys = [];
  34403. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34404. var key = _a[_i];
  34405. if (key[0] === "_") {
  34406. continue;
  34407. }
  34408. this._keys.push(key);
  34409. }
  34410. };
  34411. /**
  34412. * Specifies if two material defines are equal
  34413. * @param other - A material define instance to compare to
  34414. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34415. */
  34416. MaterialDefines.prototype.isEqual = function (other) {
  34417. if (this._keys.length !== other._keys.length) {
  34418. return false;
  34419. }
  34420. for (var index = 0; index < this._keys.length; index++) {
  34421. var prop = this._keys[index];
  34422. if (this[prop] !== other[prop]) {
  34423. return false;
  34424. }
  34425. }
  34426. return true;
  34427. };
  34428. /**
  34429. * Clones this instance's defines to another instance
  34430. * @param other - material defines to clone values to
  34431. */
  34432. MaterialDefines.prototype.cloneTo = function (other) {
  34433. if (this._keys.length !== other._keys.length) {
  34434. other._keys = this._keys.slice(0);
  34435. }
  34436. for (var index = 0; index < this._keys.length; index++) {
  34437. var prop = this._keys[index];
  34438. other[prop] = this[prop];
  34439. }
  34440. };
  34441. /**
  34442. * Resets the material define values
  34443. */
  34444. MaterialDefines.prototype.reset = function () {
  34445. for (var index = 0; index < this._keys.length; index++) {
  34446. var prop = this._keys[index];
  34447. var type = typeof this[prop];
  34448. switch (type) {
  34449. case "number":
  34450. this[prop] = 0;
  34451. break;
  34452. case "string":
  34453. this[prop] = "";
  34454. break;
  34455. default:
  34456. this[prop] = false;
  34457. break;
  34458. }
  34459. }
  34460. };
  34461. /**
  34462. * Converts the material define values to a string
  34463. * @returns - String of material define information
  34464. */
  34465. MaterialDefines.prototype.toString = function () {
  34466. var result = "";
  34467. for (var index = 0; index < this._keys.length; index++) {
  34468. var prop = this._keys[index];
  34469. var value = this[prop];
  34470. var type = typeof value;
  34471. switch (type) {
  34472. case "number":
  34473. case "string":
  34474. result += "#define " + prop + " " + value + "\n";
  34475. break;
  34476. default:
  34477. if (value) {
  34478. result += "#define " + prop + "\n";
  34479. }
  34480. break;
  34481. }
  34482. }
  34483. return result;
  34484. };
  34485. return MaterialDefines;
  34486. }());
  34487. BABYLON.MaterialDefines = MaterialDefines;
  34488. /**
  34489. * Base class for the main features of a material in Babylon.js
  34490. */
  34491. var Material = /** @class */ (function () {
  34492. /**
  34493. * Creates a material instance
  34494. * @param name defines the name of the material
  34495. * @param scene defines the scene to reference
  34496. * @param doNotAdd specifies if the material should be added to the scene
  34497. */
  34498. function Material(name, scene, doNotAdd) {
  34499. /**
  34500. * Specifies if the ready state should be checked on each call
  34501. */
  34502. this.checkReadyOnEveryCall = false;
  34503. /**
  34504. * Specifies if the ready state should be checked once
  34505. */
  34506. this.checkReadyOnlyOnce = false;
  34507. /**
  34508. * The state of the material
  34509. */
  34510. this.state = "";
  34511. /**
  34512. * The alpha value of the material
  34513. */
  34514. this._alpha = 1.0;
  34515. /**
  34516. * Specifies if back face culling is enabled
  34517. */
  34518. this._backFaceCulling = true;
  34519. /**
  34520. * Specifies if the material should be serialized
  34521. */
  34522. this.doNotSerialize = false;
  34523. /**
  34524. * Specifies if the effect should be stored on sub meshes
  34525. */
  34526. this.storeEffectOnSubMeshes = false;
  34527. /**
  34528. * An event triggered when the material is disposed
  34529. */
  34530. this.onDisposeObservable = new BABYLON.Observable();
  34531. /**
  34532. * An event triggered when the material is bound
  34533. */
  34534. this.onBindObservable = new BABYLON.Observable();
  34535. /**
  34536. * An event triggered when the material is unbound
  34537. */
  34538. this.onUnBindObservable = new BABYLON.Observable();
  34539. /**
  34540. * Stores the value of the alpha mode
  34541. */
  34542. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34543. /**
  34544. * Stores the state of the need depth pre-pass value
  34545. */
  34546. this._needDepthPrePass = false;
  34547. /**
  34548. * Specifies if depth writing should be disabled
  34549. */
  34550. this.disableDepthWrite = false;
  34551. /**
  34552. * Specifies if depth writing should be forced
  34553. */
  34554. this.forceDepthWrite = false;
  34555. /**
  34556. * Specifies if there should be a separate pass for culling
  34557. */
  34558. this.separateCullingPass = false;
  34559. /**
  34560. * Stores the state specifing if fog should be enabled
  34561. */
  34562. this._fogEnabled = true;
  34563. /**
  34564. * Stores the size of points
  34565. */
  34566. this.pointSize = 1.0;
  34567. /**
  34568. * Stores the z offset value
  34569. */
  34570. this.zOffset = 0;
  34571. /**
  34572. * Specifies if the material was previously ready
  34573. */
  34574. this._wasPreviouslyReady = false;
  34575. /**
  34576. * Stores the fill mode state
  34577. */
  34578. this._fillMode = Material.TriangleFillMode;
  34579. this.name = name;
  34580. this.id = name || BABYLON.Tools.RandomId();
  34581. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34582. this.uniqueId = this._scene.getUniqueId();
  34583. if (this._scene.useRightHandedSystem) {
  34584. this.sideOrientation = Material.ClockWiseSideOrientation;
  34585. }
  34586. else {
  34587. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34588. }
  34589. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34590. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34591. if (!doNotAdd) {
  34592. this._scene.materials.push(this);
  34593. }
  34594. }
  34595. Object.defineProperty(Material, "TriangleFillMode", {
  34596. /**
  34597. * Returns the triangle fill mode
  34598. */
  34599. get: function () {
  34600. return Material._TriangleFillMode;
  34601. },
  34602. enumerable: true,
  34603. configurable: true
  34604. });
  34605. Object.defineProperty(Material, "WireFrameFillMode", {
  34606. /**
  34607. * Returns the wireframe mode
  34608. */
  34609. get: function () {
  34610. return Material._WireFrameFillMode;
  34611. },
  34612. enumerable: true,
  34613. configurable: true
  34614. });
  34615. Object.defineProperty(Material, "PointFillMode", {
  34616. /**
  34617. * Returns the point fill mode
  34618. */
  34619. get: function () {
  34620. return Material._PointFillMode;
  34621. },
  34622. enumerable: true,
  34623. configurable: true
  34624. });
  34625. Object.defineProperty(Material, "PointListDrawMode", {
  34626. /**
  34627. * Returns the point list draw mode
  34628. */
  34629. get: function () {
  34630. return Material._PointListDrawMode;
  34631. },
  34632. enumerable: true,
  34633. configurable: true
  34634. });
  34635. Object.defineProperty(Material, "LineListDrawMode", {
  34636. /**
  34637. * Returns the line list draw mode
  34638. */
  34639. get: function () {
  34640. return Material._LineListDrawMode;
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. Object.defineProperty(Material, "LineLoopDrawMode", {
  34646. /**
  34647. * Returns the line loop draw mode
  34648. */
  34649. get: function () {
  34650. return Material._LineLoopDrawMode;
  34651. },
  34652. enumerable: true,
  34653. configurable: true
  34654. });
  34655. Object.defineProperty(Material, "LineStripDrawMode", {
  34656. /**
  34657. * Returns the line strip draw mode
  34658. */
  34659. get: function () {
  34660. return Material._LineStripDrawMode;
  34661. },
  34662. enumerable: true,
  34663. configurable: true
  34664. });
  34665. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34666. /**
  34667. * Returns the triangle strip draw mode
  34668. */
  34669. get: function () {
  34670. return Material._TriangleStripDrawMode;
  34671. },
  34672. enumerable: true,
  34673. configurable: true
  34674. });
  34675. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34676. /**
  34677. * Returns the triangle fan draw mode
  34678. */
  34679. get: function () {
  34680. return Material._TriangleFanDrawMode;
  34681. },
  34682. enumerable: true,
  34683. configurable: true
  34684. });
  34685. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34686. /**
  34687. * Returns the clock-wise side orientation
  34688. */
  34689. get: function () {
  34690. return Material._ClockWiseSideOrientation;
  34691. },
  34692. enumerable: true,
  34693. configurable: true
  34694. });
  34695. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34696. /**
  34697. * Returns the counter clock-wise side orientation
  34698. */
  34699. get: function () {
  34700. return Material._CounterClockWiseSideOrientation;
  34701. },
  34702. enumerable: true,
  34703. configurable: true
  34704. });
  34705. Object.defineProperty(Material, "TextureDirtyFlag", {
  34706. /**
  34707. * Returns the dirty texture flag value
  34708. */
  34709. get: function () {
  34710. return Material._TextureDirtyFlag;
  34711. },
  34712. enumerable: true,
  34713. configurable: true
  34714. });
  34715. Object.defineProperty(Material, "LightDirtyFlag", {
  34716. /**
  34717. * Returns the dirty light flag value
  34718. */
  34719. get: function () {
  34720. return Material._LightDirtyFlag;
  34721. },
  34722. enumerable: true,
  34723. configurable: true
  34724. });
  34725. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34726. /**
  34727. * Returns the dirty fresnel flag value
  34728. */
  34729. get: function () {
  34730. return Material._FresnelDirtyFlag;
  34731. },
  34732. enumerable: true,
  34733. configurable: true
  34734. });
  34735. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34736. /**
  34737. * Returns the dirty attributes flag value
  34738. */
  34739. get: function () {
  34740. return Material._AttributesDirtyFlag;
  34741. },
  34742. enumerable: true,
  34743. configurable: true
  34744. });
  34745. Object.defineProperty(Material, "MiscDirtyFlag", {
  34746. /**
  34747. * Returns the dirty misc flag value
  34748. */
  34749. get: function () {
  34750. return Material._MiscDirtyFlag;
  34751. },
  34752. enumerable: true,
  34753. configurable: true
  34754. });
  34755. Object.defineProperty(Material.prototype, "alpha", {
  34756. /**
  34757. * Gets the alpha value of the material
  34758. */
  34759. get: function () {
  34760. return this._alpha;
  34761. },
  34762. /**
  34763. * Sets the alpha value of the material
  34764. */
  34765. set: function (value) {
  34766. if (this._alpha === value) {
  34767. return;
  34768. }
  34769. this._alpha = value;
  34770. this.markAsDirty(Material.MiscDirtyFlag);
  34771. },
  34772. enumerable: true,
  34773. configurable: true
  34774. });
  34775. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34776. /**
  34777. * Gets the back-face culling state
  34778. */
  34779. get: function () {
  34780. return this._backFaceCulling;
  34781. },
  34782. /**
  34783. * Sets the back-face culling state
  34784. */
  34785. set: function (value) {
  34786. if (this._backFaceCulling === value) {
  34787. return;
  34788. }
  34789. this._backFaceCulling = value;
  34790. this.markAsDirty(Material.TextureDirtyFlag);
  34791. },
  34792. enumerable: true,
  34793. configurable: true
  34794. });
  34795. Object.defineProperty(Material.prototype, "onDispose", {
  34796. /**
  34797. * Called during a dispose event
  34798. */
  34799. set: function (callback) {
  34800. if (this._onDisposeObserver) {
  34801. this.onDisposeObservable.remove(this._onDisposeObserver);
  34802. }
  34803. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34804. },
  34805. enumerable: true,
  34806. configurable: true
  34807. });
  34808. Object.defineProperty(Material.prototype, "onBind", {
  34809. /**
  34810. * Called during a bind event
  34811. */
  34812. set: function (callback) {
  34813. if (this._onBindObserver) {
  34814. this.onBindObservable.remove(this._onBindObserver);
  34815. }
  34816. this._onBindObserver = this.onBindObservable.add(callback);
  34817. },
  34818. enumerable: true,
  34819. configurable: true
  34820. });
  34821. Object.defineProperty(Material.prototype, "alphaMode", {
  34822. /**
  34823. * Gets the value of the alpha mode
  34824. */
  34825. get: function () {
  34826. return this._alphaMode;
  34827. },
  34828. /**
  34829. * Sets the value of the alpha mode.
  34830. *
  34831. * | Value | Type | Description |
  34832. * | --- | --- | --- |
  34833. * | 0 | ALPHA_DISABLE | |
  34834. * | 1 | ALPHA_ADD | |
  34835. * | 2 | ALPHA_COMBINE | |
  34836. * | 3 | ALPHA_SUBTRACT | |
  34837. * | 4 | ALPHA_MULTIPLY | |
  34838. * | 5 | ALPHA_MAXIMIZED | |
  34839. * | 6 | ALPHA_ONEONE | |
  34840. * | 7 | ALPHA_PREMULTIPLIED | |
  34841. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34842. * | 9 | ALPHA_INTERPOLATE | |
  34843. * | 10 | ALPHA_SCREENMODE | |
  34844. *
  34845. */
  34846. set: function (value) {
  34847. if (this._alphaMode === value) {
  34848. return;
  34849. }
  34850. this._alphaMode = value;
  34851. this.markAsDirty(Material.TextureDirtyFlag);
  34852. },
  34853. enumerable: true,
  34854. configurable: true
  34855. });
  34856. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34857. /**
  34858. * Gets the depth pre-pass value
  34859. */
  34860. get: function () {
  34861. return this._needDepthPrePass;
  34862. },
  34863. /**
  34864. * Sets the need depth pre-pass value
  34865. */
  34866. set: function (value) {
  34867. if (this._needDepthPrePass === value) {
  34868. return;
  34869. }
  34870. this._needDepthPrePass = value;
  34871. if (this._needDepthPrePass) {
  34872. this.checkReadyOnEveryCall = true;
  34873. }
  34874. },
  34875. enumerable: true,
  34876. configurable: true
  34877. });
  34878. Object.defineProperty(Material.prototype, "fogEnabled", {
  34879. /**
  34880. * Gets the value of the fog enabled state
  34881. */
  34882. get: function () {
  34883. return this._fogEnabled;
  34884. },
  34885. /**
  34886. * Sets the state for enabling fog
  34887. */
  34888. set: function (value) {
  34889. if (this._fogEnabled === value) {
  34890. return;
  34891. }
  34892. this._fogEnabled = value;
  34893. this.markAsDirty(Material.MiscDirtyFlag);
  34894. },
  34895. enumerable: true,
  34896. configurable: true
  34897. });
  34898. Object.defineProperty(Material.prototype, "wireframe", {
  34899. /**
  34900. * Gets a value specifying if wireframe mode is enabled
  34901. */
  34902. get: function () {
  34903. switch (this._fillMode) {
  34904. case Material.WireFrameFillMode:
  34905. case Material.LineListDrawMode:
  34906. case Material.LineLoopDrawMode:
  34907. case Material.LineStripDrawMode:
  34908. return true;
  34909. }
  34910. return this._scene.forceWireframe;
  34911. },
  34912. /**
  34913. * Sets the state of wireframe mode
  34914. */
  34915. set: function (value) {
  34916. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34917. },
  34918. enumerable: true,
  34919. configurable: true
  34920. });
  34921. Object.defineProperty(Material.prototype, "pointsCloud", {
  34922. /**
  34923. * Gets the value specifying if point clouds are enabled
  34924. */
  34925. get: function () {
  34926. switch (this._fillMode) {
  34927. case Material.PointFillMode:
  34928. case Material.PointListDrawMode:
  34929. return true;
  34930. }
  34931. return this._scene.forcePointsCloud;
  34932. },
  34933. /**
  34934. * Sets the state of point cloud mode
  34935. */
  34936. set: function (value) {
  34937. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34938. },
  34939. enumerable: true,
  34940. configurable: true
  34941. });
  34942. Object.defineProperty(Material.prototype, "fillMode", {
  34943. /**
  34944. * Gets the material fill mode
  34945. */
  34946. get: function () {
  34947. return this._fillMode;
  34948. },
  34949. /**
  34950. * Sets the material fill mode
  34951. */
  34952. set: function (value) {
  34953. if (this._fillMode === value) {
  34954. return;
  34955. }
  34956. this._fillMode = value;
  34957. this.markAsDirty(Material.MiscDirtyFlag);
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. /**
  34963. * Returns a string representation of the current material
  34964. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34965. * @returns a string with material information
  34966. */
  34967. Material.prototype.toString = function (fullDetails) {
  34968. var ret = "Name: " + this.name;
  34969. if (fullDetails) {
  34970. }
  34971. return ret;
  34972. };
  34973. /**
  34974. * Gets the class name of the material
  34975. * @returns a string with the class name of the material
  34976. */
  34977. Material.prototype.getClassName = function () {
  34978. return "Material";
  34979. };
  34980. Object.defineProperty(Material.prototype, "isFrozen", {
  34981. /**
  34982. * Specifies if updates for the material been locked
  34983. */
  34984. get: function () {
  34985. return this.checkReadyOnlyOnce;
  34986. },
  34987. enumerable: true,
  34988. configurable: true
  34989. });
  34990. /**
  34991. * Locks updates for the material
  34992. */
  34993. Material.prototype.freeze = function () {
  34994. this.checkReadyOnlyOnce = true;
  34995. };
  34996. /**
  34997. * Unlocks updates for the material
  34998. */
  34999. Material.prototype.unfreeze = function () {
  35000. this.checkReadyOnlyOnce = false;
  35001. };
  35002. /**
  35003. * Specifies if the material is ready to be used
  35004. * @param mesh defines the mesh to check
  35005. * @param useInstances specifies if instances should be used
  35006. * @returns a boolean indicating if the material is ready to be used
  35007. */
  35008. Material.prototype.isReady = function (mesh, useInstances) {
  35009. return true;
  35010. };
  35011. /**
  35012. * Specifies that the submesh is ready to be used
  35013. * @param mesh defines the mesh to check
  35014. * @param subMesh defines which submesh to check
  35015. * @param useInstances specifies that instances should be used
  35016. * @returns a boolean indicating that the submesh is ready or not
  35017. */
  35018. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35019. return false;
  35020. };
  35021. /**
  35022. * Returns the material effect
  35023. * @returns the effect associated with the material
  35024. */
  35025. Material.prototype.getEffect = function () {
  35026. return this._effect;
  35027. };
  35028. /**
  35029. * Returns the current scene
  35030. * @returns a Scene
  35031. */
  35032. Material.prototype.getScene = function () {
  35033. return this._scene;
  35034. };
  35035. /**
  35036. * Specifies if the material will require alpha blending
  35037. * @returns a boolean specifying if alpha blending is needed
  35038. */
  35039. Material.prototype.needAlphaBlending = function () {
  35040. return (this.alpha < 1.0);
  35041. };
  35042. /**
  35043. * Specifies if the mesh will require alpha blending
  35044. * @param mesh defines the mesh to check
  35045. * @returns a boolean specifying if alpha blending is needed for the mesh
  35046. */
  35047. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35048. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35049. };
  35050. /**
  35051. * Specifies if this material should be rendered in alpha test mode
  35052. * @returns a boolean specifying if an alpha test is needed.
  35053. */
  35054. Material.prototype.needAlphaTesting = function () {
  35055. return false;
  35056. };
  35057. /**
  35058. * Gets the texture used for the alpha test
  35059. * @returns the texture to use for alpha testing
  35060. */
  35061. Material.prototype.getAlphaTestTexture = function () {
  35062. return null;
  35063. };
  35064. /**
  35065. * Marks the material to indicate that it needs to be re-calculated
  35066. */
  35067. Material.prototype.markDirty = function () {
  35068. this._wasPreviouslyReady = false;
  35069. };
  35070. /** @hidden */
  35071. Material.prototype._preBind = function (effect, overrideOrientation) {
  35072. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35073. var engine = this._scene.getEngine();
  35074. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35075. var reverse = orientation === Material.ClockWiseSideOrientation;
  35076. engine.enableEffect(effect ? effect : this._effect);
  35077. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35078. return reverse;
  35079. };
  35080. /**
  35081. * Binds the material to the mesh
  35082. * @param world defines the world transformation matrix
  35083. * @param mesh defines the mesh to bind the material to
  35084. */
  35085. Material.prototype.bind = function (world, mesh) {
  35086. };
  35087. /**
  35088. * Binds the submesh to the material
  35089. * @param world defines the world transformation matrix
  35090. * @param mesh defines the mesh containing the submesh
  35091. * @param subMesh defines the submesh to bind the material to
  35092. */
  35093. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35094. };
  35095. /**
  35096. * Binds the world matrix to the material
  35097. * @param world defines the world transformation matrix
  35098. */
  35099. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35100. };
  35101. /**
  35102. * Binds the scene's uniform buffer to the effect.
  35103. * @param effect defines the effect to bind to the scene uniform buffer
  35104. * @param sceneUbo defines the uniform buffer storing scene data
  35105. */
  35106. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35107. sceneUbo.bindToEffect(effect, "Scene");
  35108. };
  35109. /**
  35110. * Binds the view matrix to the effect
  35111. * @param effect defines the effect to bind the view matrix to
  35112. */
  35113. Material.prototype.bindView = function (effect) {
  35114. if (!this._useUBO) {
  35115. effect.setMatrix("view", this.getScene().getViewMatrix());
  35116. }
  35117. else {
  35118. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35119. }
  35120. };
  35121. /**
  35122. * Binds the view projection matrix to the effect
  35123. * @param effect defines the effect to bind the view projection matrix to
  35124. */
  35125. Material.prototype.bindViewProjection = function (effect) {
  35126. if (!this._useUBO) {
  35127. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35128. }
  35129. else {
  35130. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35131. }
  35132. };
  35133. /**
  35134. * Specifies if material alpha testing should be turned on for the mesh
  35135. * @param mesh defines the mesh to check
  35136. */
  35137. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35138. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35139. };
  35140. /**
  35141. * Processes to execute after binding the material to a mesh
  35142. * @param mesh defines the rendered mesh
  35143. */
  35144. Material.prototype._afterBind = function (mesh) {
  35145. this._scene._cachedMaterial = this;
  35146. if (mesh) {
  35147. this._scene._cachedVisibility = mesh.visibility;
  35148. }
  35149. else {
  35150. this._scene._cachedVisibility = 1;
  35151. }
  35152. if (mesh) {
  35153. this.onBindObservable.notifyObservers(mesh);
  35154. }
  35155. if (this.disableDepthWrite) {
  35156. var engine = this._scene.getEngine();
  35157. this._cachedDepthWriteState = engine.getDepthWrite();
  35158. engine.setDepthWrite(false);
  35159. }
  35160. };
  35161. /**
  35162. * Unbinds the material from the mesh
  35163. */
  35164. Material.prototype.unbind = function () {
  35165. this.onUnBindObservable.notifyObservers(this);
  35166. if (this.disableDepthWrite) {
  35167. var engine = this._scene.getEngine();
  35168. engine.setDepthWrite(this._cachedDepthWriteState);
  35169. }
  35170. };
  35171. /**
  35172. * Gets the active textures from the material
  35173. * @returns an array of textures
  35174. */
  35175. Material.prototype.getActiveTextures = function () {
  35176. return [];
  35177. };
  35178. /**
  35179. * Specifies if the material uses a texture
  35180. * @param texture defines the texture to check against the material
  35181. * @returns a boolean specifying if the material uses the texture
  35182. */
  35183. Material.prototype.hasTexture = function (texture) {
  35184. return false;
  35185. };
  35186. /**
  35187. * Makes a duplicate of the material, and gives it a new name
  35188. * @param name defines the new name for the duplicated material
  35189. * @returns the cloned material
  35190. */
  35191. Material.prototype.clone = function (name) {
  35192. return null;
  35193. };
  35194. /**
  35195. * Gets the meshes bound to the material
  35196. * @returns an array of meshes bound to the material
  35197. */
  35198. Material.prototype.getBindedMeshes = function () {
  35199. var result = new Array();
  35200. for (var index = 0; index < this._scene.meshes.length; index++) {
  35201. var mesh = this._scene.meshes[index];
  35202. if (mesh.material === this) {
  35203. result.push(mesh);
  35204. }
  35205. }
  35206. return result;
  35207. };
  35208. /**
  35209. * Force shader compilation
  35210. * @param mesh defines the mesh associated with this material
  35211. * @param onCompiled defines a function to execute once the material is compiled
  35212. * @param options defines the options to configure the compilation
  35213. */
  35214. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35215. var _this = this;
  35216. var localOptions = __assign({ clipPlane: false }, options);
  35217. var subMesh = new BABYLON.BaseSubMesh();
  35218. var scene = this.getScene();
  35219. var checkReady = function () {
  35220. if (!_this._scene || !_this._scene.getEngine()) {
  35221. return;
  35222. }
  35223. if (subMesh._materialDefines) {
  35224. subMesh._materialDefines._renderId = -1;
  35225. }
  35226. var clipPlaneState = scene.clipPlane;
  35227. if (localOptions.clipPlane) {
  35228. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35229. }
  35230. if (_this.storeEffectOnSubMeshes) {
  35231. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35232. if (onCompiled) {
  35233. onCompiled(_this);
  35234. }
  35235. }
  35236. else {
  35237. setTimeout(checkReady, 16);
  35238. }
  35239. }
  35240. else {
  35241. if (_this.isReady(mesh)) {
  35242. if (onCompiled) {
  35243. onCompiled(_this);
  35244. }
  35245. }
  35246. else {
  35247. setTimeout(checkReady, 16);
  35248. }
  35249. }
  35250. if (localOptions.clipPlane) {
  35251. scene.clipPlane = clipPlaneState;
  35252. }
  35253. };
  35254. checkReady();
  35255. };
  35256. /**
  35257. * Force shader compilation
  35258. * @param mesh defines the mesh that will use this material
  35259. * @param options defines additional options for compiling the shaders
  35260. * @returns a promise that resolves when the compilation completes
  35261. */
  35262. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35263. var _this = this;
  35264. return new Promise(function (resolve) {
  35265. _this.forceCompilation(mesh, function () {
  35266. resolve();
  35267. }, options);
  35268. });
  35269. };
  35270. /**
  35271. * Marks a define in the material to indicate that it needs to be re-computed
  35272. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35273. */
  35274. Material.prototype.markAsDirty = function (flag) {
  35275. if (flag & Material.TextureDirtyFlag) {
  35276. this._markAllSubMeshesAsTexturesDirty();
  35277. }
  35278. if (flag & Material.LightDirtyFlag) {
  35279. this._markAllSubMeshesAsLightsDirty();
  35280. }
  35281. if (flag & Material.FresnelDirtyFlag) {
  35282. this._markAllSubMeshesAsFresnelDirty();
  35283. }
  35284. if (flag & Material.AttributesDirtyFlag) {
  35285. this._markAllSubMeshesAsAttributesDirty();
  35286. }
  35287. if (flag & Material.MiscDirtyFlag) {
  35288. this._markAllSubMeshesAsMiscDirty();
  35289. }
  35290. this.getScene().resetCachedMaterial();
  35291. };
  35292. /**
  35293. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35294. * @param func defines a function which checks material defines against the submeshes
  35295. */
  35296. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35297. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35298. var mesh = _a[_i];
  35299. if (!mesh.subMeshes) {
  35300. continue;
  35301. }
  35302. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35303. var subMesh = _c[_b];
  35304. if (subMesh.getMaterial() !== this) {
  35305. continue;
  35306. }
  35307. if (!subMesh._materialDefines) {
  35308. continue;
  35309. }
  35310. func(subMesh._materialDefines);
  35311. }
  35312. }
  35313. };
  35314. /**
  35315. * Indicates that image processing needs to be re-calculated for all submeshes
  35316. */
  35317. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35318. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35319. };
  35320. /**
  35321. * Indicates that textures need to be re-calculated for all submeshes
  35322. */
  35323. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35324. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35325. };
  35326. /**
  35327. * Indicates that fresnel needs to be re-calculated for all submeshes
  35328. */
  35329. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35330. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35331. };
  35332. /**
  35333. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35334. */
  35335. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35336. this._markAllSubMeshesAsDirty(function (defines) {
  35337. defines.markAsFresnelDirty();
  35338. defines.markAsMiscDirty();
  35339. });
  35340. };
  35341. /**
  35342. * Indicates that lights need to be re-calculated for all submeshes
  35343. */
  35344. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35345. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35346. };
  35347. /**
  35348. * Indicates that attributes need to be re-calculated for all submeshes
  35349. */
  35350. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35351. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35352. };
  35353. /**
  35354. * Indicates that misc needs to be re-calculated for all submeshes
  35355. */
  35356. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35357. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35358. };
  35359. /**
  35360. * Indicates that textures and misc need to be re-calculated for all submeshes
  35361. */
  35362. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35363. this._markAllSubMeshesAsDirty(function (defines) {
  35364. defines.markAsTexturesDirty();
  35365. defines.markAsMiscDirty();
  35366. });
  35367. };
  35368. /**
  35369. * Disposes the material
  35370. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35371. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35372. */
  35373. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35374. // Animations
  35375. this.getScene().stopAnimation(this);
  35376. this.getScene().freeProcessedMaterials();
  35377. // Remove from scene
  35378. var index = this._scene.materials.indexOf(this);
  35379. if (index >= 0) {
  35380. this._scene.materials.splice(index, 1);
  35381. }
  35382. // Remove from meshes
  35383. for (index = 0; index < this._scene.meshes.length; index++) {
  35384. var mesh = this._scene.meshes[index];
  35385. if (mesh.material === this) {
  35386. mesh.material = null;
  35387. if (mesh.geometry) {
  35388. var geometry = (mesh.geometry);
  35389. if (this.storeEffectOnSubMeshes) {
  35390. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35391. var subMesh = _a[_i];
  35392. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35393. if (forceDisposeEffect && subMesh._materialEffect) {
  35394. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35395. }
  35396. }
  35397. }
  35398. else {
  35399. geometry._releaseVertexArrayObject(this._effect);
  35400. }
  35401. }
  35402. }
  35403. }
  35404. this._uniformBuffer.dispose();
  35405. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35406. if (forceDisposeEffect && this._effect) {
  35407. if (!this.storeEffectOnSubMeshes) {
  35408. this._scene.getEngine()._releaseEffect(this._effect);
  35409. }
  35410. this._effect = null;
  35411. }
  35412. // Callback
  35413. this.onDisposeObservable.notifyObservers(this);
  35414. this.onDisposeObservable.clear();
  35415. this.onBindObservable.clear();
  35416. this.onUnBindObservable.clear();
  35417. };
  35418. /**
  35419. * Serializes this material
  35420. * @returns the serialized material object
  35421. */
  35422. Material.prototype.serialize = function () {
  35423. return BABYLON.SerializationHelper.Serialize(this);
  35424. };
  35425. /**
  35426. * Creates a MultiMaterial from parsed MultiMaterial data.
  35427. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35428. * @param scene defines the hosting scene
  35429. * @returns a new MultiMaterial
  35430. */
  35431. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35432. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35433. multiMaterial.id = parsedMultiMaterial.id;
  35434. if (BABYLON.Tags) {
  35435. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35436. }
  35437. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35438. var subMatId = parsedMultiMaterial.materials[matIndex];
  35439. if (subMatId) {
  35440. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35441. }
  35442. else {
  35443. multiMaterial.subMaterials.push(null);
  35444. }
  35445. }
  35446. return multiMaterial;
  35447. };
  35448. /**
  35449. * Creates a material from parsed material data
  35450. * @param parsedMaterial defines parsed material data
  35451. * @param scene defines the hosting scene
  35452. * @param rootUrl defines the root URL to use to load textures
  35453. * @returns a new material
  35454. */
  35455. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35456. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35457. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35458. }
  35459. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35460. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35461. if (!BABYLON.LegacyPBRMaterial) {
  35462. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35463. return;
  35464. }
  35465. }
  35466. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35467. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35468. };
  35469. // Triangle views
  35470. Material._TriangleFillMode = 0;
  35471. Material._WireFrameFillMode = 1;
  35472. Material._PointFillMode = 2;
  35473. // Draw modes
  35474. Material._PointListDrawMode = 3;
  35475. Material._LineListDrawMode = 4;
  35476. Material._LineLoopDrawMode = 5;
  35477. Material._LineStripDrawMode = 6;
  35478. Material._TriangleStripDrawMode = 7;
  35479. Material._TriangleFanDrawMode = 8;
  35480. /**
  35481. * Stores the clock-wise side orientation
  35482. */
  35483. Material._ClockWiseSideOrientation = 0;
  35484. /**
  35485. * Stores the counter clock-wise side orientation
  35486. */
  35487. Material._CounterClockWiseSideOrientation = 1;
  35488. /**
  35489. * The dirty texture flag value
  35490. */
  35491. Material._TextureDirtyFlag = 1;
  35492. /**
  35493. * The dirty light flag value
  35494. */
  35495. Material._LightDirtyFlag = 2;
  35496. /**
  35497. * The dirty fresnel flag value
  35498. */
  35499. Material._FresnelDirtyFlag = 4;
  35500. /**
  35501. * The dirty attribute flag value
  35502. */
  35503. Material._AttributesDirtyFlag = 8;
  35504. /**
  35505. * The dirty misc flag value
  35506. */
  35507. Material._MiscDirtyFlag = 16;
  35508. __decorate([
  35509. BABYLON.serialize()
  35510. ], Material.prototype, "id", void 0);
  35511. __decorate([
  35512. BABYLON.serialize()
  35513. ], Material.prototype, "uniqueId", void 0);
  35514. __decorate([
  35515. BABYLON.serialize()
  35516. ], Material.prototype, "name", void 0);
  35517. __decorate([
  35518. BABYLON.serialize()
  35519. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35520. __decorate([
  35521. BABYLON.serialize()
  35522. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35523. __decorate([
  35524. BABYLON.serialize()
  35525. ], Material.prototype, "state", void 0);
  35526. __decorate([
  35527. BABYLON.serialize("alpha")
  35528. ], Material.prototype, "_alpha", void 0);
  35529. __decorate([
  35530. BABYLON.serialize("backFaceCulling")
  35531. ], Material.prototype, "_backFaceCulling", void 0);
  35532. __decorate([
  35533. BABYLON.serialize()
  35534. ], Material.prototype, "sideOrientation", void 0);
  35535. __decorate([
  35536. BABYLON.serialize("alphaMode")
  35537. ], Material.prototype, "_alphaMode", void 0);
  35538. __decorate([
  35539. BABYLON.serialize()
  35540. ], Material.prototype, "_needDepthPrePass", void 0);
  35541. __decorate([
  35542. BABYLON.serialize()
  35543. ], Material.prototype, "disableDepthWrite", void 0);
  35544. __decorate([
  35545. BABYLON.serialize()
  35546. ], Material.prototype, "forceDepthWrite", void 0);
  35547. __decorate([
  35548. BABYLON.serialize()
  35549. ], Material.prototype, "separateCullingPass", void 0);
  35550. __decorate([
  35551. BABYLON.serialize("fogEnabled")
  35552. ], Material.prototype, "_fogEnabled", void 0);
  35553. __decorate([
  35554. BABYLON.serialize()
  35555. ], Material.prototype, "pointSize", void 0);
  35556. __decorate([
  35557. BABYLON.serialize()
  35558. ], Material.prototype, "zOffset", void 0);
  35559. __decorate([
  35560. BABYLON.serialize()
  35561. ], Material.prototype, "wireframe", null);
  35562. __decorate([
  35563. BABYLON.serialize()
  35564. ], Material.prototype, "pointsCloud", null);
  35565. __decorate([
  35566. BABYLON.serialize()
  35567. ], Material.prototype, "fillMode", null);
  35568. return Material;
  35569. }());
  35570. BABYLON.Material = Material;
  35571. })(BABYLON || (BABYLON = {}));
  35572. //# sourceMappingURL=babylon.material.js.map
  35573. var BABYLON;
  35574. (function (BABYLON) {
  35575. var UniformBuffer = /** @class */ (function () {
  35576. /**
  35577. * Uniform buffer objects.
  35578. *
  35579. * Handles blocks of uniform on the GPU.
  35580. *
  35581. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35582. *
  35583. * For more information, please refer to :
  35584. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35585. */
  35586. function UniformBuffer(engine, data, dynamic) {
  35587. this._engine = engine;
  35588. this._noUBO = !engine.supportsUniformBuffers;
  35589. this._dynamic = dynamic;
  35590. this._data = data || [];
  35591. this._uniformLocations = {};
  35592. this._uniformSizes = {};
  35593. this._uniformLocationPointer = 0;
  35594. this._needSync = false;
  35595. if (this._noUBO) {
  35596. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35597. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35598. this.updateFloat = this._updateFloatForEffect;
  35599. this.updateFloat2 = this._updateFloat2ForEffect;
  35600. this.updateFloat3 = this._updateFloat3ForEffect;
  35601. this.updateFloat4 = this._updateFloat4ForEffect;
  35602. this.updateMatrix = this._updateMatrixForEffect;
  35603. this.updateVector3 = this._updateVector3ForEffect;
  35604. this.updateVector4 = this._updateVector4ForEffect;
  35605. this.updateColor3 = this._updateColor3ForEffect;
  35606. this.updateColor4 = this._updateColor4ForEffect;
  35607. }
  35608. else {
  35609. this._engine._uniformBuffers.push(this);
  35610. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35611. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35612. this.updateFloat = this._updateFloatForUniform;
  35613. this.updateFloat2 = this._updateFloat2ForUniform;
  35614. this.updateFloat3 = this._updateFloat3ForUniform;
  35615. this.updateFloat4 = this._updateFloat4ForUniform;
  35616. this.updateMatrix = this._updateMatrixForUniform;
  35617. this.updateVector3 = this._updateVector3ForUniform;
  35618. this.updateVector4 = this._updateVector4ForUniform;
  35619. this.updateColor3 = this._updateColor3ForUniform;
  35620. this.updateColor4 = this._updateColor4ForUniform;
  35621. }
  35622. }
  35623. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35624. // Properties
  35625. /**
  35626. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35627. * or just falling back on setUniformXXX calls.
  35628. */
  35629. get: function () {
  35630. return !this._noUBO;
  35631. },
  35632. enumerable: true,
  35633. configurable: true
  35634. });
  35635. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35636. /**
  35637. * Indicates if the WebGL underlying uniform buffer is in sync
  35638. * with the javascript cache data.
  35639. */
  35640. get: function () {
  35641. return !this._needSync;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. /**
  35647. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35648. * Also, a dynamic UniformBuffer will disable cache verification and always
  35649. * update the underlying WebGL uniform buffer to the GPU.
  35650. */
  35651. UniformBuffer.prototype.isDynamic = function () {
  35652. return this._dynamic !== undefined;
  35653. };
  35654. /**
  35655. * The data cache on JS side.
  35656. */
  35657. UniformBuffer.prototype.getData = function () {
  35658. return this._bufferData;
  35659. };
  35660. /**
  35661. * The underlying WebGL Uniform buffer.
  35662. */
  35663. UniformBuffer.prototype.getBuffer = function () {
  35664. return this._buffer;
  35665. };
  35666. /**
  35667. * std140 layout specifies how to align data within an UBO structure.
  35668. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35669. * for specs.
  35670. */
  35671. UniformBuffer.prototype._fillAlignment = function (size) {
  35672. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35673. // and 4x4 matrices
  35674. // TODO : change if other types are used
  35675. var alignment;
  35676. if (size <= 2) {
  35677. alignment = size;
  35678. }
  35679. else {
  35680. alignment = 4;
  35681. }
  35682. if ((this._uniformLocationPointer % alignment) !== 0) {
  35683. var oldPointer = this._uniformLocationPointer;
  35684. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35685. var diff = this._uniformLocationPointer - oldPointer;
  35686. for (var i = 0; i < diff; i++) {
  35687. this._data.push(0);
  35688. }
  35689. }
  35690. };
  35691. /**
  35692. * Adds an uniform in the buffer.
  35693. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35694. * for the layout to be correct !
  35695. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35696. * @param {number|number[]} size Data size, or data directly.
  35697. */
  35698. UniformBuffer.prototype.addUniform = function (name, size) {
  35699. if (this._noUBO) {
  35700. return;
  35701. }
  35702. if (this._uniformLocations[name] !== undefined) {
  35703. // Already existing uniform
  35704. return;
  35705. }
  35706. // This function must be called in the order of the shader layout !
  35707. // size can be the size of the uniform, or data directly
  35708. var data;
  35709. if (size instanceof Array) {
  35710. data = size;
  35711. size = data.length;
  35712. }
  35713. else {
  35714. size = size;
  35715. data = [];
  35716. // Fill with zeros
  35717. for (var i = 0; i < size; i++) {
  35718. data.push(0);
  35719. }
  35720. }
  35721. this._fillAlignment(size);
  35722. this._uniformSizes[name] = size;
  35723. this._uniformLocations[name] = this._uniformLocationPointer;
  35724. this._uniformLocationPointer += size;
  35725. for (var i = 0; i < size; i++) {
  35726. this._data.push(data[i]);
  35727. }
  35728. this._needSync = true;
  35729. };
  35730. /**
  35731. * Wrapper for addUniform.
  35732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35733. * @param {Matrix} mat A 4x4 matrix.
  35734. */
  35735. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35736. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35737. };
  35738. /**
  35739. * Wrapper for addUniform.
  35740. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35741. * @param {number} x
  35742. * @param {number} y
  35743. */
  35744. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35745. var temp = [x, y];
  35746. this.addUniform(name, temp);
  35747. };
  35748. /**
  35749. * Wrapper for addUniform.
  35750. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35751. * @param {number} x
  35752. * @param {number} y
  35753. * @param {number} z
  35754. */
  35755. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35756. var temp = [x, y, z];
  35757. this.addUniform(name, temp);
  35758. };
  35759. /**
  35760. * Wrapper for addUniform.
  35761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35762. * @param {Color3} color
  35763. */
  35764. UniformBuffer.prototype.addColor3 = function (name, color) {
  35765. var temp = new Array();
  35766. color.toArray(temp);
  35767. this.addUniform(name, temp);
  35768. };
  35769. /**
  35770. * Wrapper for addUniform.
  35771. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35772. * @param {Color3} color
  35773. * @param {number} alpha
  35774. */
  35775. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35776. var temp = new Array();
  35777. color.toArray(temp);
  35778. temp.push(alpha);
  35779. this.addUniform(name, temp);
  35780. };
  35781. /**
  35782. * Wrapper for addUniform.
  35783. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35784. * @param {Vector3} vector
  35785. */
  35786. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35787. var temp = new Array();
  35788. vector.toArray(temp);
  35789. this.addUniform(name, temp);
  35790. };
  35791. /**
  35792. * Wrapper for addUniform.
  35793. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35794. */
  35795. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35796. this.addUniform(name, 12);
  35797. };
  35798. /**
  35799. * Wrapper for addUniform.
  35800. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35801. */
  35802. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35803. this.addUniform(name, 8);
  35804. };
  35805. /**
  35806. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35807. */
  35808. UniformBuffer.prototype.create = function () {
  35809. if (this._noUBO) {
  35810. return;
  35811. }
  35812. if (this._buffer) {
  35813. return; // nothing to do
  35814. }
  35815. // See spec, alignment must be filled as a vec4
  35816. this._fillAlignment(4);
  35817. this._bufferData = new Float32Array(this._data);
  35818. this._rebuild();
  35819. this._needSync = true;
  35820. };
  35821. UniformBuffer.prototype._rebuild = function () {
  35822. if (this._noUBO) {
  35823. return;
  35824. }
  35825. if (this._dynamic) {
  35826. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35827. }
  35828. else {
  35829. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35830. }
  35831. };
  35832. /**
  35833. * Updates the WebGL Uniform Buffer on the GPU.
  35834. * If the `dynamic` flag is set to true, no cache comparison is done.
  35835. * Otherwise, the buffer will be updated only if the cache differs.
  35836. */
  35837. UniformBuffer.prototype.update = function () {
  35838. if (!this._buffer) {
  35839. this.create();
  35840. return;
  35841. }
  35842. if (!this._dynamic && !this._needSync) {
  35843. return;
  35844. }
  35845. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35846. this._needSync = false;
  35847. };
  35848. /**
  35849. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35850. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35851. * @param {number[]|Float32Array} data Flattened data
  35852. * @param {number} size Size of the data.
  35853. */
  35854. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35855. var location = this._uniformLocations[uniformName];
  35856. if (location === undefined) {
  35857. if (this._buffer) {
  35858. // Cannot add an uniform if the buffer is already created
  35859. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35860. return;
  35861. }
  35862. this.addUniform(uniformName, size);
  35863. location = this._uniformLocations[uniformName];
  35864. }
  35865. if (!this._buffer) {
  35866. this.create();
  35867. }
  35868. if (!this._dynamic) {
  35869. // Cache for static uniform buffers
  35870. var changed = false;
  35871. for (var i = 0; i < size; i++) {
  35872. if (this._bufferData[location + i] !== data[i]) {
  35873. changed = true;
  35874. this._bufferData[location + i] = data[i];
  35875. }
  35876. }
  35877. this._needSync = this._needSync || changed;
  35878. }
  35879. else {
  35880. // No cache for dynamic
  35881. for (var i = 0; i < size; i++) {
  35882. this._bufferData[location + i] = data[i];
  35883. }
  35884. }
  35885. };
  35886. // Update methods
  35887. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35888. // To match std140, matrix must be realigned
  35889. for (var i = 0; i < 3; i++) {
  35890. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35891. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35892. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35893. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35894. }
  35895. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35896. };
  35897. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35898. this._currentEffect.setMatrix3x3(name, matrix);
  35899. };
  35900. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35901. this._currentEffect.setMatrix2x2(name, matrix);
  35902. };
  35903. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35904. // To match std140, matrix must be realigned
  35905. for (var i = 0; i < 2; i++) {
  35906. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35907. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35908. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35909. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35910. }
  35911. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35912. };
  35913. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35914. this._currentEffect.setFloat(name, x);
  35915. };
  35916. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35917. UniformBuffer._tempBuffer[0] = x;
  35918. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35919. };
  35920. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35921. if (suffix === void 0) { suffix = ""; }
  35922. this._currentEffect.setFloat2(name + suffix, x, y);
  35923. };
  35924. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35925. if (suffix === void 0) { suffix = ""; }
  35926. UniformBuffer._tempBuffer[0] = x;
  35927. UniformBuffer._tempBuffer[1] = y;
  35928. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35929. };
  35930. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35931. if (suffix === void 0) { suffix = ""; }
  35932. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35933. };
  35934. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35935. if (suffix === void 0) { suffix = ""; }
  35936. UniformBuffer._tempBuffer[0] = x;
  35937. UniformBuffer._tempBuffer[1] = y;
  35938. UniformBuffer._tempBuffer[2] = z;
  35939. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35940. };
  35941. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35942. if (suffix === void 0) { suffix = ""; }
  35943. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35944. };
  35945. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35946. if (suffix === void 0) { suffix = ""; }
  35947. UniformBuffer._tempBuffer[0] = x;
  35948. UniformBuffer._tempBuffer[1] = y;
  35949. UniformBuffer._tempBuffer[2] = z;
  35950. UniformBuffer._tempBuffer[3] = w;
  35951. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35952. };
  35953. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35954. this._currentEffect.setMatrix(name, mat);
  35955. };
  35956. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35957. this.updateUniform(name, mat.toArray(), 16);
  35958. };
  35959. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35960. this._currentEffect.setVector3(name, vector);
  35961. };
  35962. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35963. vector.toArray(UniformBuffer._tempBuffer);
  35964. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35965. };
  35966. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35967. this._currentEffect.setVector4(name, vector);
  35968. };
  35969. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35970. vector.toArray(UniformBuffer._tempBuffer);
  35971. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35972. };
  35973. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35974. if (suffix === void 0) { suffix = ""; }
  35975. this._currentEffect.setColor3(name + suffix, color);
  35976. };
  35977. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35978. if (suffix === void 0) { suffix = ""; }
  35979. color.toArray(UniformBuffer._tempBuffer);
  35980. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35981. };
  35982. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35983. if (suffix === void 0) { suffix = ""; }
  35984. this._currentEffect.setColor4(name + suffix, color, alpha);
  35985. };
  35986. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35987. if (suffix === void 0) { suffix = ""; }
  35988. color.toArray(UniformBuffer._tempBuffer);
  35989. UniformBuffer._tempBuffer[3] = alpha;
  35990. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35991. };
  35992. /**
  35993. * Sets a sampler uniform on the effect.
  35994. * @param {string} name Name of the sampler.
  35995. * @param {Texture} texture
  35996. */
  35997. UniformBuffer.prototype.setTexture = function (name, texture) {
  35998. this._currentEffect.setTexture(name, texture);
  35999. };
  36000. /**
  36001. * Directly updates the value of the uniform in the cache AND on the GPU.
  36002. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36003. * @param {number[]|Float32Array} data Flattened data
  36004. */
  36005. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36006. this.updateUniform(uniformName, data, data.length);
  36007. this.update();
  36008. };
  36009. /**
  36010. * Binds this uniform buffer to an effect.
  36011. * @param {Effect} effect
  36012. * @param {string} name Name of the uniform block in the shader.
  36013. */
  36014. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36015. this._currentEffect = effect;
  36016. if (this._noUBO || !this._buffer) {
  36017. return;
  36018. }
  36019. effect.bindUniformBuffer(this._buffer, name);
  36020. };
  36021. /**
  36022. * Disposes the uniform buffer.
  36023. */
  36024. UniformBuffer.prototype.dispose = function () {
  36025. if (this._noUBO) {
  36026. return;
  36027. }
  36028. var index = this._engine._uniformBuffers.indexOf(this);
  36029. if (index !== -1) {
  36030. this._engine._uniformBuffers.splice(index, 1);
  36031. }
  36032. if (!this._buffer) {
  36033. return;
  36034. }
  36035. if (this._engine._releaseBuffer(this._buffer)) {
  36036. this._buffer = null;
  36037. }
  36038. };
  36039. // Pool for avoiding memory leaks
  36040. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36041. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36042. return UniformBuffer;
  36043. }());
  36044. BABYLON.UniformBuffer = UniformBuffer;
  36045. })(BABYLON || (BABYLON = {}));
  36046. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36047. var BABYLON;
  36048. (function (BABYLON) {
  36049. /**
  36050. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36051. */
  36052. var VertexData = /** @class */ (function () {
  36053. function VertexData() {
  36054. }
  36055. /**
  36056. * Uses the passed data array to set the set the values for the specified kind of data
  36057. * @param data a linear array of floating numbers
  36058. * @param kind the type of data that is being set, eg positions, colors etc
  36059. */
  36060. VertexData.prototype.set = function (data, kind) {
  36061. switch (kind) {
  36062. case BABYLON.VertexBuffer.PositionKind:
  36063. this.positions = data;
  36064. break;
  36065. case BABYLON.VertexBuffer.NormalKind:
  36066. this.normals = data;
  36067. break;
  36068. case BABYLON.VertexBuffer.TangentKind:
  36069. this.tangents = data;
  36070. break;
  36071. case BABYLON.VertexBuffer.UVKind:
  36072. this.uvs = data;
  36073. break;
  36074. case BABYLON.VertexBuffer.UV2Kind:
  36075. this.uvs2 = data;
  36076. break;
  36077. case BABYLON.VertexBuffer.UV3Kind:
  36078. this.uvs3 = data;
  36079. break;
  36080. case BABYLON.VertexBuffer.UV4Kind:
  36081. this.uvs4 = data;
  36082. break;
  36083. case BABYLON.VertexBuffer.UV5Kind:
  36084. this.uvs5 = data;
  36085. break;
  36086. case BABYLON.VertexBuffer.UV6Kind:
  36087. this.uvs6 = data;
  36088. break;
  36089. case BABYLON.VertexBuffer.ColorKind:
  36090. this.colors = data;
  36091. break;
  36092. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36093. this.matricesIndices = data;
  36094. break;
  36095. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36096. this.matricesWeights = data;
  36097. break;
  36098. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36099. this.matricesIndicesExtra = data;
  36100. break;
  36101. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36102. this.matricesWeightsExtra = data;
  36103. break;
  36104. }
  36105. };
  36106. /**
  36107. * Associates the vertexData to the passed Mesh.
  36108. * Sets it as updatable or not (default `false`)
  36109. * @param mesh the mesh the vertexData is applied to
  36110. * @param updatable when used and having the value true allows new data to update the vertexData
  36111. * @returns the VertexData
  36112. */
  36113. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36114. this._applyTo(mesh, updatable);
  36115. return this;
  36116. };
  36117. /**
  36118. * Associates the vertexData to the passed Geometry.
  36119. * Sets it as updatable or not (default `false`)
  36120. * @param geometry the geometry the vertexData is applied to
  36121. * @param updatable when used and having the value true allows new data to update the vertexData
  36122. * @returns VertexData
  36123. */
  36124. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36125. this._applyTo(geometry, updatable);
  36126. return this;
  36127. };
  36128. /**
  36129. * Updates the associated mesh
  36130. * @param mesh the mesh to be updated
  36131. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36132. * @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
  36133. * @returns VertexData
  36134. */
  36135. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36136. this._update(mesh);
  36137. return this;
  36138. };
  36139. /**
  36140. * Updates the associated geometry
  36141. * @param geometry the geometry to be updated
  36142. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36143. * @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
  36144. * @returns VertexData.
  36145. */
  36146. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36147. this._update(geometry);
  36148. return this;
  36149. };
  36150. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36151. if (updatable === void 0) { updatable = false; }
  36152. if (this.positions) {
  36153. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36154. }
  36155. if (this.normals) {
  36156. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36157. }
  36158. if (this.tangents) {
  36159. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36160. }
  36161. if (this.uvs) {
  36162. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36163. }
  36164. if (this.uvs2) {
  36165. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36166. }
  36167. if (this.uvs3) {
  36168. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36169. }
  36170. if (this.uvs4) {
  36171. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36172. }
  36173. if (this.uvs5) {
  36174. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36175. }
  36176. if (this.uvs6) {
  36177. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36178. }
  36179. if (this.colors) {
  36180. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36181. }
  36182. if (this.matricesIndices) {
  36183. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36184. }
  36185. if (this.matricesWeights) {
  36186. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36187. }
  36188. if (this.matricesIndicesExtra) {
  36189. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36190. }
  36191. if (this.matricesWeightsExtra) {
  36192. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36193. }
  36194. if (this.indices) {
  36195. meshOrGeometry.setIndices(this.indices, null, updatable);
  36196. }
  36197. else {
  36198. meshOrGeometry.setIndices([], null);
  36199. }
  36200. return this;
  36201. };
  36202. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36203. if (this.positions) {
  36204. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36205. }
  36206. if (this.normals) {
  36207. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36208. }
  36209. if (this.tangents) {
  36210. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36211. }
  36212. if (this.uvs) {
  36213. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36214. }
  36215. if (this.uvs2) {
  36216. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36217. }
  36218. if (this.uvs3) {
  36219. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36220. }
  36221. if (this.uvs4) {
  36222. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36223. }
  36224. if (this.uvs5) {
  36225. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36226. }
  36227. if (this.uvs6) {
  36228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36229. }
  36230. if (this.colors) {
  36231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36232. }
  36233. if (this.matricesIndices) {
  36234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36235. }
  36236. if (this.matricesWeights) {
  36237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36238. }
  36239. if (this.matricesIndicesExtra) {
  36240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36241. }
  36242. if (this.matricesWeightsExtra) {
  36243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36244. }
  36245. if (this.indices) {
  36246. meshOrGeometry.setIndices(this.indices, null);
  36247. }
  36248. return this;
  36249. };
  36250. /**
  36251. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36252. * @param matrix the transforming matrix
  36253. * @returns the VertexData
  36254. */
  36255. VertexData.prototype.transform = function (matrix) {
  36256. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36257. var transformed = BABYLON.Vector3.Zero();
  36258. var index;
  36259. if (this.positions) {
  36260. var position = BABYLON.Vector3.Zero();
  36261. for (index = 0; index < this.positions.length; index += 3) {
  36262. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36263. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36264. this.positions[index] = transformed.x;
  36265. this.positions[index + 1] = transformed.y;
  36266. this.positions[index + 2] = transformed.z;
  36267. }
  36268. }
  36269. if (this.normals) {
  36270. var normal = BABYLON.Vector3.Zero();
  36271. for (index = 0; index < this.normals.length; index += 3) {
  36272. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36273. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36274. this.normals[index] = transformed.x;
  36275. this.normals[index + 1] = transformed.y;
  36276. this.normals[index + 2] = transformed.z;
  36277. }
  36278. }
  36279. if (this.tangents) {
  36280. var tangent = BABYLON.Vector4.Zero();
  36281. var tangentTransformed = BABYLON.Vector4.Zero();
  36282. for (index = 0; index < this.tangents.length; index += 4) {
  36283. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36284. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36285. this.tangents[index] = tangentTransformed.x;
  36286. this.tangents[index + 1] = tangentTransformed.y;
  36287. this.tangents[index + 2] = tangentTransformed.z;
  36288. this.tangents[index + 3] = tangentTransformed.w;
  36289. }
  36290. }
  36291. if (flip && this.indices) {
  36292. for (index = 0; index < this.indices.length; index += 3) {
  36293. var tmp = this.indices[index + 1];
  36294. this.indices[index + 1] = this.indices[index + 2];
  36295. this.indices[index + 2] = tmp;
  36296. }
  36297. }
  36298. return this;
  36299. };
  36300. /**
  36301. * Merges the passed VertexData into the current one
  36302. * @param other the VertexData to be merged into the current one
  36303. * @returns the modified VertexData
  36304. */
  36305. VertexData.prototype.merge = function (other) {
  36306. this._validate();
  36307. other._validate();
  36308. if (!this.normals !== !other.normals ||
  36309. !this.tangents !== !other.tangents ||
  36310. !this.uvs !== !other.uvs ||
  36311. !this.uvs2 !== !other.uvs2 ||
  36312. !this.uvs3 !== !other.uvs3 ||
  36313. !this.uvs4 !== !other.uvs4 ||
  36314. !this.uvs5 !== !other.uvs5 ||
  36315. !this.uvs6 !== !other.uvs6 ||
  36316. !this.colors !== !other.colors ||
  36317. !this.matricesIndices !== !other.matricesIndices ||
  36318. !this.matricesWeights !== !other.matricesWeights ||
  36319. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36320. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36321. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36322. }
  36323. if (other.indices) {
  36324. if (!this.indices) {
  36325. this.indices = [];
  36326. }
  36327. var offset = this.positions ? this.positions.length / 3 : 0;
  36328. for (var index = 0; index < other.indices.length; index++) {
  36329. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36330. this.indices.push(other.indices[index] + offset);
  36331. }
  36332. }
  36333. this.positions = this._mergeElement(this.positions, other.positions);
  36334. this.normals = this._mergeElement(this.normals, other.normals);
  36335. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36336. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36337. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36338. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36339. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36340. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36341. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36342. this.colors = this._mergeElement(this.colors, other.colors);
  36343. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36344. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36345. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36346. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36347. return this;
  36348. };
  36349. VertexData.prototype._mergeElement = function (source, other) {
  36350. if (!source) {
  36351. return other;
  36352. }
  36353. if (!other) {
  36354. return source;
  36355. }
  36356. var len = other.length + source.length;
  36357. var isSrcTypedArray = source instanceof Float32Array;
  36358. var isOthTypedArray = other instanceof Float32Array;
  36359. // use non-loop method when the source is Float32Array
  36360. if (isSrcTypedArray) {
  36361. var ret32 = new Float32Array(len);
  36362. ret32.set(source);
  36363. ret32.set(other, source.length);
  36364. return ret32;
  36365. // source is number[], when other is also use concat
  36366. }
  36367. else if (!isOthTypedArray) {
  36368. return source.concat(other);
  36369. // source is a number[], but other is a Float32Array, loop required
  36370. }
  36371. else {
  36372. var ret = source.slice(0); // copy source to a separate array
  36373. for (var i = 0, len = other.length; i < len; i++) {
  36374. ret.push(other[i]);
  36375. }
  36376. return ret;
  36377. }
  36378. };
  36379. VertexData.prototype._validate = function () {
  36380. if (!this.positions) {
  36381. throw new Error("Positions are required");
  36382. }
  36383. var getElementCount = function (kind, values) {
  36384. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36385. if ((values.length % stride) !== 0) {
  36386. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36387. }
  36388. return values.length / stride;
  36389. };
  36390. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36391. var validateElementCount = function (kind, values) {
  36392. var elementCount = getElementCount(kind, values);
  36393. if (elementCount !== positionsElementCount) {
  36394. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36395. }
  36396. };
  36397. if (this.normals)
  36398. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36399. if (this.tangents)
  36400. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36401. if (this.uvs)
  36402. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36403. if (this.uvs2)
  36404. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36405. if (this.uvs3)
  36406. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36407. if (this.uvs4)
  36408. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36409. if (this.uvs5)
  36410. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36411. if (this.uvs6)
  36412. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36413. if (this.colors)
  36414. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36415. if (this.matricesIndices)
  36416. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36417. if (this.matricesWeights)
  36418. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36419. if (this.matricesIndicesExtra)
  36420. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36421. if (this.matricesWeightsExtra)
  36422. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36423. };
  36424. /**
  36425. * Serializes the VertexData
  36426. * @returns a serialized object
  36427. */
  36428. VertexData.prototype.serialize = function () {
  36429. var serializationObject = this.serialize();
  36430. if (this.positions) {
  36431. serializationObject.positions = this.positions;
  36432. }
  36433. if (this.normals) {
  36434. serializationObject.normals = this.normals;
  36435. }
  36436. if (this.tangents) {
  36437. serializationObject.tangents = this.tangents;
  36438. }
  36439. if (this.uvs) {
  36440. serializationObject.uvs = this.uvs;
  36441. }
  36442. if (this.uvs2) {
  36443. serializationObject.uvs2 = this.uvs2;
  36444. }
  36445. if (this.uvs3) {
  36446. serializationObject.uvs3 = this.uvs3;
  36447. }
  36448. if (this.uvs4) {
  36449. serializationObject.uvs4 = this.uvs4;
  36450. }
  36451. if (this.uvs5) {
  36452. serializationObject.uvs5 = this.uvs5;
  36453. }
  36454. if (this.uvs6) {
  36455. serializationObject.uvs6 = this.uvs6;
  36456. }
  36457. if (this.colors) {
  36458. serializationObject.colors = this.colors;
  36459. }
  36460. if (this.matricesIndices) {
  36461. serializationObject.matricesIndices = this.matricesIndices;
  36462. serializationObject.matricesIndices._isExpanded = true;
  36463. }
  36464. if (this.matricesWeights) {
  36465. serializationObject.matricesWeights = this.matricesWeights;
  36466. }
  36467. if (this.matricesIndicesExtra) {
  36468. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36469. serializationObject.matricesIndicesExtra._isExpanded = true;
  36470. }
  36471. if (this.matricesWeightsExtra) {
  36472. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36473. }
  36474. serializationObject.indices = this.indices;
  36475. return serializationObject;
  36476. };
  36477. // Statics
  36478. /**
  36479. * Extracts the vertexData from a mesh
  36480. * @param mesh the mesh from which to extract the VertexData
  36481. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36482. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36483. * @returns the object VertexData associated to the passed mesh
  36484. */
  36485. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36486. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36487. };
  36488. /**
  36489. * Extracts the vertexData from the geometry
  36490. * @param geometry the geometry from which to extract the VertexData
  36491. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36492. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36493. * @returns the object VertexData associated to the passed mesh
  36494. */
  36495. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36496. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36497. };
  36498. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36499. var result = new VertexData();
  36500. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36501. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36502. }
  36503. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36504. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36505. }
  36506. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36507. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36508. }
  36509. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36510. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36511. }
  36512. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36513. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36514. }
  36515. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36516. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36517. }
  36518. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36519. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36520. }
  36521. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36522. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36523. }
  36524. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36525. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36526. }
  36527. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36528. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36529. }
  36530. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36531. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36532. }
  36533. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36534. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36535. }
  36536. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36537. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36538. }
  36539. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36540. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36541. }
  36542. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36543. return result;
  36544. };
  36545. /**
  36546. * Creates the VertexData for a Ribbon
  36547. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36548. * * pathArray array of paths, each of which an array of successive Vector3
  36549. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36550. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36551. * * 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
  36552. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36553. * * 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)
  36554. * * 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)
  36555. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36556. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36557. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36558. * @returns the VertexData of the ribbon
  36559. */
  36560. VertexData.CreateRibbon = function (options) {
  36561. var pathArray = options.pathArray;
  36562. var closeArray = options.closeArray || false;
  36563. var closePath = options.closePath || false;
  36564. var invertUV = options.invertUV || false;
  36565. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36566. var offset = options.offset || defaultOffset;
  36567. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36568. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36569. var customUV = options.uvs;
  36570. var customColors = options.colors;
  36571. var positions = [];
  36572. var indices = [];
  36573. var normals = [];
  36574. var uvs = [];
  36575. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36576. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36577. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36578. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36579. var minlg; // minimal length among all paths from pathArray
  36580. var lg = []; // array of path lengths : nb of vertex per path
  36581. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36582. var p; // path iterator
  36583. var i; // point iterator
  36584. var j; // point iterator
  36585. // if single path in pathArray
  36586. if (pathArray.length < 2) {
  36587. var ar1 = [];
  36588. var ar2 = [];
  36589. for (i = 0; i < pathArray[0].length - offset; i++) {
  36590. ar1.push(pathArray[0][i]);
  36591. ar2.push(pathArray[0][i + offset]);
  36592. }
  36593. pathArray = [ar1, ar2];
  36594. }
  36595. // positions and horizontal distances (u)
  36596. var idc = 0;
  36597. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36598. var path;
  36599. var l;
  36600. minlg = pathArray[0].length;
  36601. var vectlg;
  36602. var dist;
  36603. for (p = 0; p < pathArray.length; p++) {
  36604. uTotalDistance[p] = 0;
  36605. us[p] = [0];
  36606. path = pathArray[p];
  36607. l = path.length;
  36608. minlg = (minlg < l) ? minlg : l;
  36609. j = 0;
  36610. while (j < l) {
  36611. positions.push(path[j].x, path[j].y, path[j].z);
  36612. if (j > 0) {
  36613. vectlg = path[j].subtract(path[j - 1]).length();
  36614. dist = vectlg + uTotalDistance[p];
  36615. us[p].push(dist);
  36616. uTotalDistance[p] = dist;
  36617. }
  36618. j++;
  36619. }
  36620. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36621. j--;
  36622. positions.push(path[0].x, path[0].y, path[0].z);
  36623. vectlg = path[j].subtract(path[0]).length();
  36624. dist = vectlg + uTotalDistance[p];
  36625. us[p].push(dist);
  36626. uTotalDistance[p] = dist;
  36627. }
  36628. lg[p] = l + closePathCorr;
  36629. idx[p] = idc;
  36630. idc += (l + closePathCorr);
  36631. }
  36632. // vertical distances (v)
  36633. var path1;
  36634. var path2;
  36635. var vertex1 = null;
  36636. var vertex2 = null;
  36637. for (i = 0; i < minlg + closePathCorr; i++) {
  36638. vTotalDistance[i] = 0;
  36639. vs[i] = [0];
  36640. for (p = 0; p < pathArray.length - 1; p++) {
  36641. path1 = pathArray[p];
  36642. path2 = pathArray[p + 1];
  36643. if (i === minlg) { // closePath
  36644. vertex1 = path1[0];
  36645. vertex2 = path2[0];
  36646. }
  36647. else {
  36648. vertex1 = path1[i];
  36649. vertex2 = path2[i];
  36650. }
  36651. vectlg = vertex2.subtract(vertex1).length();
  36652. dist = vectlg + vTotalDistance[i];
  36653. vs[i].push(dist);
  36654. vTotalDistance[i] = dist;
  36655. }
  36656. if (closeArray && vertex2 && vertex1) {
  36657. path1 = pathArray[p];
  36658. path2 = pathArray[0];
  36659. if (i === minlg) { // closePath
  36660. vertex2 = path2[0];
  36661. }
  36662. vectlg = vertex2.subtract(vertex1).length();
  36663. dist = vectlg + vTotalDistance[i];
  36664. vTotalDistance[i] = dist;
  36665. }
  36666. }
  36667. // uvs
  36668. var u;
  36669. var v;
  36670. if (customUV) {
  36671. for (p = 0; p < customUV.length; p++) {
  36672. uvs.push(customUV[p].x, customUV[p].y);
  36673. }
  36674. }
  36675. else {
  36676. for (p = 0; p < pathArray.length; p++) {
  36677. for (i = 0; i < minlg + closePathCorr; i++) {
  36678. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36679. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36680. if (invertUV) {
  36681. uvs.push(v, u);
  36682. }
  36683. else {
  36684. uvs.push(u, v);
  36685. }
  36686. }
  36687. }
  36688. }
  36689. // indices
  36690. p = 0; // path index
  36691. var pi = 0; // positions array index
  36692. var l1 = lg[p] - 1; // path1 length
  36693. var l2 = lg[p + 1] - 1; // path2 length
  36694. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36695. var shft = idx[1] - idx[0]; // shift
  36696. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36697. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36698. // 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
  36699. indices.push(pi, pi + shft, pi + 1);
  36700. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36701. pi += 1;
  36702. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36703. p++;
  36704. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36705. shft = idx[0] - idx[p];
  36706. l1 = lg[p] - 1;
  36707. l2 = lg[0] - 1;
  36708. }
  36709. else {
  36710. shft = idx[p + 1] - idx[p];
  36711. l1 = lg[p] - 1;
  36712. l2 = lg[p + 1] - 1;
  36713. }
  36714. pi = idx[p];
  36715. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36716. }
  36717. }
  36718. // normals
  36719. VertexData.ComputeNormals(positions, indices, normals);
  36720. if (closePath) { // update both the first and last vertex normals to their average value
  36721. var indexFirst = 0;
  36722. var indexLast = 0;
  36723. for (p = 0; p < pathArray.length; p++) {
  36724. indexFirst = idx[p] * 3;
  36725. if (p + 1 < pathArray.length) {
  36726. indexLast = (idx[p + 1] - 1) * 3;
  36727. }
  36728. else {
  36729. indexLast = normals.length - 3;
  36730. }
  36731. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36732. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36733. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36734. normals[indexLast] = normals[indexFirst];
  36735. normals[indexLast + 1] = normals[indexFirst + 1];
  36736. normals[indexLast + 2] = normals[indexFirst + 2];
  36737. }
  36738. }
  36739. // sides
  36740. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36741. // Colors
  36742. var colors = null;
  36743. if (customColors) {
  36744. colors = new Float32Array(customColors.length * 4);
  36745. for (var c = 0; c < customColors.length; c++) {
  36746. colors[c * 4] = customColors[c].r;
  36747. colors[c * 4 + 1] = customColors[c].g;
  36748. colors[c * 4 + 2] = customColors[c].b;
  36749. colors[c * 4 + 3] = customColors[c].a;
  36750. }
  36751. }
  36752. // Result
  36753. var vertexData = new VertexData();
  36754. var positions32 = new Float32Array(positions);
  36755. var normals32 = new Float32Array(normals);
  36756. var uvs32 = new Float32Array(uvs);
  36757. vertexData.indices = indices;
  36758. vertexData.positions = positions32;
  36759. vertexData.normals = normals32;
  36760. vertexData.uvs = uvs32;
  36761. if (colors) {
  36762. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36763. }
  36764. if (closePath) {
  36765. vertexData._idx = idx;
  36766. }
  36767. return vertexData;
  36768. };
  36769. /**
  36770. * Creates the VertexData for a box
  36771. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36772. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36773. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36774. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36775. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36776. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36777. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36778. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36779. * * 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)
  36780. * * 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)
  36781. * @returns the VertexData of the box
  36782. */
  36783. VertexData.CreateBox = function (options) {
  36784. var normalsSource = [
  36785. new BABYLON.Vector3(0, 0, 1),
  36786. new BABYLON.Vector3(0, 0, -1),
  36787. new BABYLON.Vector3(1, 0, 0),
  36788. new BABYLON.Vector3(-1, 0, 0),
  36789. new BABYLON.Vector3(0, 1, 0),
  36790. new BABYLON.Vector3(0, -1, 0)
  36791. ];
  36792. var indices = [];
  36793. var positions = [];
  36794. var normals = [];
  36795. var uvs = [];
  36796. var width = options.width || options.size || 1;
  36797. var height = options.height || options.size || 1;
  36798. var depth = options.depth || options.size || 1;
  36799. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36800. var faceUV = options.faceUV || new Array(6);
  36801. var faceColors = options.faceColors;
  36802. var colors = [];
  36803. // default face colors and UV if undefined
  36804. for (var f = 0; f < 6; f++) {
  36805. if (faceUV[f] === undefined) {
  36806. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36807. }
  36808. if (faceColors && faceColors[f] === undefined) {
  36809. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36810. }
  36811. }
  36812. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36813. // Create each face in turn.
  36814. for (var index = 0; index < normalsSource.length; index++) {
  36815. var normal = normalsSource[index];
  36816. // Get two vectors perpendicular to the face normal and to each other.
  36817. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36818. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36819. // Six indices (two triangles) per face.
  36820. var verticesLength = positions.length / 3;
  36821. indices.push(verticesLength);
  36822. indices.push(verticesLength + 1);
  36823. indices.push(verticesLength + 2);
  36824. indices.push(verticesLength);
  36825. indices.push(verticesLength + 2);
  36826. indices.push(verticesLength + 3);
  36827. // Four vertices per face.
  36828. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36829. positions.push(vertex.x, vertex.y, vertex.z);
  36830. normals.push(normal.x, normal.y, normal.z);
  36831. uvs.push(faceUV[index].z, faceUV[index].w);
  36832. if (faceColors) {
  36833. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36834. }
  36835. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36836. positions.push(vertex.x, vertex.y, vertex.z);
  36837. normals.push(normal.x, normal.y, normal.z);
  36838. uvs.push(faceUV[index].x, faceUV[index].w);
  36839. if (faceColors) {
  36840. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36841. }
  36842. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36843. positions.push(vertex.x, vertex.y, vertex.z);
  36844. normals.push(normal.x, normal.y, normal.z);
  36845. uvs.push(faceUV[index].x, faceUV[index].y);
  36846. if (faceColors) {
  36847. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36848. }
  36849. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36850. positions.push(vertex.x, vertex.y, vertex.z);
  36851. normals.push(normal.x, normal.y, normal.z);
  36852. uvs.push(faceUV[index].z, faceUV[index].y);
  36853. if (faceColors) {
  36854. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36855. }
  36856. }
  36857. // sides
  36858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36859. // Result
  36860. var vertexData = new VertexData();
  36861. vertexData.indices = indices;
  36862. vertexData.positions = positions;
  36863. vertexData.normals = normals;
  36864. vertexData.uvs = uvs;
  36865. if (faceColors) {
  36866. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36867. vertexData.colors = totalColors;
  36868. }
  36869. return vertexData;
  36870. };
  36871. /**
  36872. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36873. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36874. * * segments sets the number of horizontal strips optional, default 32
  36875. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36876. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36877. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36878. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36879. * * 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
  36880. * * 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
  36881. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36882. * * 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)
  36883. * * 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)
  36884. * @returns the VertexData of the ellipsoid
  36885. */
  36886. VertexData.CreateSphere = function (options) {
  36887. var segments = options.segments || 32;
  36888. var diameterX = options.diameterX || options.diameter || 1;
  36889. var diameterY = options.diameterY || options.diameter || 1;
  36890. var diameterZ = options.diameterZ || options.diameter || 1;
  36891. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36892. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36893. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36894. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36895. var totalZRotationSteps = 2 + segments;
  36896. var totalYRotationSteps = 2 * totalZRotationSteps;
  36897. var indices = [];
  36898. var positions = [];
  36899. var normals = [];
  36900. var uvs = [];
  36901. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36902. var normalizedZ = zRotationStep / totalZRotationSteps;
  36903. var angleZ = normalizedZ * Math.PI * slice;
  36904. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36905. var normalizedY = yRotationStep / totalYRotationSteps;
  36906. var angleY = normalizedY * Math.PI * 2 * arc;
  36907. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36908. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36909. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36910. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36911. var vertex = complete.multiply(radius);
  36912. var normal = complete.divide(radius).normalize();
  36913. positions.push(vertex.x, vertex.y, vertex.z);
  36914. normals.push(normal.x, normal.y, normal.z);
  36915. uvs.push(normalizedY, normalizedZ);
  36916. }
  36917. if (zRotationStep > 0) {
  36918. var verticesCount = positions.length / 3;
  36919. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36920. indices.push((firstIndex));
  36921. indices.push((firstIndex + 1));
  36922. indices.push(firstIndex + totalYRotationSteps + 1);
  36923. indices.push((firstIndex + totalYRotationSteps + 1));
  36924. indices.push((firstIndex + 1));
  36925. indices.push((firstIndex + totalYRotationSteps + 2));
  36926. }
  36927. }
  36928. }
  36929. // Sides
  36930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36931. // Result
  36932. var vertexData = new VertexData();
  36933. vertexData.indices = indices;
  36934. vertexData.positions = positions;
  36935. vertexData.normals = normals;
  36936. vertexData.uvs = uvs;
  36937. return vertexData;
  36938. };
  36939. /**
  36940. * Creates the VertexData for a cylinder, cone or prism
  36941. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36942. * * height sets the height (y direction) of the cylinder, optional, default 2
  36943. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36944. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36945. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36946. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36947. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36948. * * 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
  36949. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36950. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36951. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36952. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36953. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36954. * * 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)
  36955. * * 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)
  36956. * @returns the VertexData of the cylinder, cone or prism
  36957. */
  36958. VertexData.CreateCylinder = function (options) {
  36959. var height = options.height || 2;
  36960. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36961. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36962. var tessellation = options.tessellation || 24;
  36963. var subdivisions = options.subdivisions || 1;
  36964. var hasRings = options.hasRings ? true : false;
  36965. var enclose = options.enclose ? true : false;
  36966. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36967. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36968. var faceUV = options.faceUV || new Array(3);
  36969. var faceColors = options.faceColors;
  36970. // default face colors and UV if undefined
  36971. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36972. var ringNb = (hasRings) ? subdivisions : 1;
  36973. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36974. var f;
  36975. for (f = 0; f < surfaceNb; f++) {
  36976. if (faceColors && faceColors[f] === undefined) {
  36977. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36978. }
  36979. }
  36980. for (f = 0; f < surfaceNb; f++) {
  36981. if (faceUV && faceUV[f] === undefined) {
  36982. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36983. }
  36984. }
  36985. var indices = new Array();
  36986. var positions = new Array();
  36987. var normals = new Array();
  36988. var uvs = new Array();
  36989. var colors = new Array();
  36990. var angle_step = Math.PI * 2 * arc / tessellation;
  36991. var angle;
  36992. var h;
  36993. var radius;
  36994. var tan = (diameterBottom - diameterTop) / 2 / height;
  36995. var ringVertex = BABYLON.Vector3.Zero();
  36996. var ringNormal = BABYLON.Vector3.Zero();
  36997. var ringFirstVertex = BABYLON.Vector3.Zero();
  36998. var ringFirstNormal = BABYLON.Vector3.Zero();
  36999. var quadNormal = BABYLON.Vector3.Zero();
  37000. var Y = BABYLON.Axis.Y;
  37001. // positions, normals, uvs
  37002. var i;
  37003. var j;
  37004. var r;
  37005. var ringIdx = 1;
  37006. var s = 1; // surface index
  37007. var cs = 0;
  37008. var v = 0;
  37009. for (i = 0; i <= subdivisions; i++) {
  37010. h = i / subdivisions;
  37011. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37012. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37013. for (r = 0; r < ringIdx; r++) {
  37014. if (hasRings) {
  37015. s += r;
  37016. }
  37017. if (enclose) {
  37018. s += 2 * r;
  37019. }
  37020. for (j = 0; j <= tessellation; j++) {
  37021. angle = j * angle_step;
  37022. // position
  37023. ringVertex.x = Math.cos(-angle) * radius;
  37024. ringVertex.y = -height / 2 + h * height;
  37025. ringVertex.z = Math.sin(-angle) * radius;
  37026. // normal
  37027. if (diameterTop === 0 && i === subdivisions) {
  37028. // if no top cap, reuse former normals
  37029. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37030. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37031. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37032. }
  37033. else {
  37034. ringNormal.x = ringVertex.x;
  37035. ringNormal.z = ringVertex.z;
  37036. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37037. ringNormal.normalize();
  37038. }
  37039. // keep first ring vertex values for enclose
  37040. if (j === 0) {
  37041. ringFirstVertex.copyFrom(ringVertex);
  37042. ringFirstNormal.copyFrom(ringNormal);
  37043. }
  37044. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37045. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37046. if (hasRings) {
  37047. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37048. }
  37049. else {
  37050. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37051. }
  37052. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37053. if (faceColors) {
  37054. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37055. }
  37056. }
  37057. // if enclose, add four vertices and their dedicated normals
  37058. if (arc !== 1 && enclose) {
  37059. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37060. positions.push(0, ringVertex.y, 0);
  37061. positions.push(0, ringVertex.y, 0);
  37062. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37063. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37064. quadNormal.normalize();
  37065. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37066. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37067. quadNormal.normalize();
  37068. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37069. if (hasRings) {
  37070. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37071. }
  37072. else {
  37073. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37074. }
  37075. uvs.push(faceUV[s + 1].x, v);
  37076. uvs.push(faceUV[s + 1].z, v);
  37077. if (hasRings) {
  37078. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37079. }
  37080. else {
  37081. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37082. }
  37083. uvs.push(faceUV[s + 2].x, v);
  37084. uvs.push(faceUV[s + 2].z, v);
  37085. if (faceColors) {
  37086. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37087. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37088. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37089. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37090. }
  37091. }
  37092. if (cs !== s) {
  37093. cs = s;
  37094. }
  37095. }
  37096. }
  37097. // indices
  37098. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37099. var s;
  37100. i = 0;
  37101. for (s = 0; s < subdivisions; s++) {
  37102. var i0 = 0;
  37103. var i1 = 0;
  37104. var i2 = 0;
  37105. var i3 = 0;
  37106. for (j = 0; j < tessellation; j++) {
  37107. i0 = i * (e + 1) + j;
  37108. i1 = (i + 1) * (e + 1) + j;
  37109. i2 = i * (e + 1) + (j + 1);
  37110. i3 = (i + 1) * (e + 1) + (j + 1);
  37111. indices.push(i0, i1, i2);
  37112. indices.push(i3, i2, i1);
  37113. }
  37114. if (arc !== 1 && enclose) { // if enclose, add two quads
  37115. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37116. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37117. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37118. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37119. }
  37120. i = (hasRings) ? (i + 2) : (i + 1);
  37121. }
  37122. // Caps
  37123. var createCylinderCap = function (isTop) {
  37124. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37125. if (radius === 0) {
  37126. return;
  37127. }
  37128. // Cap positions, normals & uvs
  37129. var angle;
  37130. var circleVector;
  37131. var i;
  37132. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37133. var c = null;
  37134. if (faceColors) {
  37135. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37136. }
  37137. // cap center
  37138. var vbase = positions.length / 3;
  37139. var offset = isTop ? height / 2 : -height / 2;
  37140. var center = new BABYLON.Vector3(0, offset, 0);
  37141. positions.push(center.x, center.y, center.z);
  37142. normals.push(0, isTop ? 1 : -1, 0);
  37143. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37144. if (c) {
  37145. colors.push(c.r, c.g, c.b, c.a);
  37146. }
  37147. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37148. for (i = 0; i <= tessellation; i++) {
  37149. angle = Math.PI * 2 * i * arc / tessellation;
  37150. var cos = Math.cos(-angle);
  37151. var sin = Math.sin(-angle);
  37152. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37153. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37154. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37155. normals.push(0, isTop ? 1 : -1, 0);
  37156. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37157. if (c) {
  37158. colors.push(c.r, c.g, c.b, c.a);
  37159. }
  37160. }
  37161. // Cap indices
  37162. for (i = 0; i < tessellation; i++) {
  37163. if (!isTop) {
  37164. indices.push(vbase);
  37165. indices.push(vbase + (i + 1));
  37166. indices.push(vbase + (i + 2));
  37167. }
  37168. else {
  37169. indices.push(vbase);
  37170. indices.push(vbase + (i + 2));
  37171. indices.push(vbase + (i + 1));
  37172. }
  37173. }
  37174. };
  37175. // add caps to geometry
  37176. createCylinderCap(false);
  37177. createCylinderCap(true);
  37178. // Sides
  37179. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37180. var vertexData = new VertexData();
  37181. vertexData.indices = indices;
  37182. vertexData.positions = positions;
  37183. vertexData.normals = normals;
  37184. vertexData.uvs = uvs;
  37185. if (faceColors) {
  37186. vertexData.colors = colors;
  37187. }
  37188. return vertexData;
  37189. };
  37190. /**
  37191. * Creates the VertexData for a torus
  37192. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37193. * * diameter the diameter of the torus, optional default 1
  37194. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37195. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37196. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37197. * * 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)
  37198. * * 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)
  37199. * @returns the VertexData of the torus
  37200. */
  37201. VertexData.CreateTorus = function (options) {
  37202. var indices = [];
  37203. var positions = [];
  37204. var normals = [];
  37205. var uvs = [];
  37206. var diameter = options.diameter || 1;
  37207. var thickness = options.thickness || 0.5;
  37208. var tessellation = options.tessellation || 16;
  37209. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37210. var stride = tessellation + 1;
  37211. for (var i = 0; i <= tessellation; i++) {
  37212. var u = i / tessellation;
  37213. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37214. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37215. for (var j = 0; j <= tessellation; j++) {
  37216. var v = 1 - j / tessellation;
  37217. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37218. var dx = Math.cos(innerAngle);
  37219. var dy = Math.sin(innerAngle);
  37220. // Create a vertex.
  37221. var normal = new BABYLON.Vector3(dx, dy, 0);
  37222. var position = normal.scale(thickness / 2);
  37223. var textureCoordinate = new BABYLON.Vector2(u, v);
  37224. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37225. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37226. positions.push(position.x, position.y, position.z);
  37227. normals.push(normal.x, normal.y, normal.z);
  37228. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37229. // And create indices for two triangles.
  37230. var nextI = (i + 1) % stride;
  37231. var nextJ = (j + 1) % stride;
  37232. indices.push(i * stride + j);
  37233. indices.push(i * stride + nextJ);
  37234. indices.push(nextI * stride + j);
  37235. indices.push(i * stride + nextJ);
  37236. indices.push(nextI * stride + nextJ);
  37237. indices.push(nextI * stride + j);
  37238. }
  37239. }
  37240. // Sides
  37241. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37242. // Result
  37243. var vertexData = new VertexData();
  37244. vertexData.indices = indices;
  37245. vertexData.positions = positions;
  37246. vertexData.normals = normals;
  37247. vertexData.uvs = uvs;
  37248. return vertexData;
  37249. };
  37250. /**
  37251. * Creates the VertexData of the LineSystem
  37252. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37253. * - lines an array of lines, each line being an array of successive Vector3
  37254. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37255. * @returns the VertexData of the LineSystem
  37256. */
  37257. VertexData.CreateLineSystem = function (options) {
  37258. var indices = [];
  37259. var positions = [];
  37260. var lines = options.lines;
  37261. var colors = options.colors;
  37262. var vertexColors = [];
  37263. var idx = 0;
  37264. for (var l = 0; l < lines.length; l++) {
  37265. var points = lines[l];
  37266. for (var index = 0; index < points.length; index++) {
  37267. positions.push(points[index].x, points[index].y, points[index].z);
  37268. if (colors) {
  37269. var color = colors[l];
  37270. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37271. }
  37272. if (index > 0) {
  37273. indices.push(idx - 1);
  37274. indices.push(idx);
  37275. }
  37276. idx++;
  37277. }
  37278. }
  37279. var vertexData = new VertexData();
  37280. vertexData.indices = indices;
  37281. vertexData.positions = positions;
  37282. if (colors) {
  37283. vertexData.colors = vertexColors;
  37284. }
  37285. return vertexData;
  37286. };
  37287. /**
  37288. * Create the VertexData for a DashedLines
  37289. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37290. * - points an array successive Vector3
  37291. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37292. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37293. * - dashNb the intended total number of dashes, optional, default 200
  37294. * @returns the VertexData for the DashedLines
  37295. */
  37296. VertexData.CreateDashedLines = function (options) {
  37297. var dashSize = options.dashSize || 3;
  37298. var gapSize = options.gapSize || 1;
  37299. var dashNb = options.dashNb || 200;
  37300. var points = options.points;
  37301. var positions = new Array();
  37302. var indices = new Array();
  37303. var curvect = BABYLON.Vector3.Zero();
  37304. var lg = 0;
  37305. var nb = 0;
  37306. var shft = 0;
  37307. var dashshft = 0;
  37308. var curshft = 0;
  37309. var idx = 0;
  37310. var i = 0;
  37311. for (i = 0; i < points.length - 1; i++) {
  37312. points[i + 1].subtractToRef(points[i], curvect);
  37313. lg += curvect.length();
  37314. }
  37315. shft = lg / dashNb;
  37316. dashshft = dashSize * shft / (dashSize + gapSize);
  37317. for (i = 0; i < points.length - 1; i++) {
  37318. points[i + 1].subtractToRef(points[i], curvect);
  37319. nb = Math.floor(curvect.length() / shft);
  37320. curvect.normalize();
  37321. for (var j = 0; j < nb; j++) {
  37322. curshft = shft * j;
  37323. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37324. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37325. indices.push(idx, idx + 1);
  37326. idx += 2;
  37327. }
  37328. }
  37329. // Result
  37330. var vertexData = new VertexData();
  37331. vertexData.positions = positions;
  37332. vertexData.indices = indices;
  37333. return vertexData;
  37334. };
  37335. /**
  37336. * Creates the VertexData for a Ground
  37337. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37338. * - width the width (x direction) of the ground, optional, default 1
  37339. * - height the height (z direction) of the ground, optional, default 1
  37340. * - subdivisions the number of subdivisions per side, optional, default 1
  37341. * @returns the VertexData of the Ground
  37342. */
  37343. VertexData.CreateGround = function (options) {
  37344. var indices = [];
  37345. var positions = [];
  37346. var normals = [];
  37347. var uvs = [];
  37348. var row, col;
  37349. var width = options.width || 1;
  37350. var height = options.height || 1;
  37351. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37352. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37353. for (row = 0; row <= subdivisionsY; row++) {
  37354. for (col = 0; col <= subdivisionsX; col++) {
  37355. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37356. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37357. positions.push(position.x, position.y, position.z);
  37358. normals.push(normal.x, normal.y, normal.z);
  37359. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37360. }
  37361. }
  37362. for (row = 0; row < subdivisionsY; row++) {
  37363. for (col = 0; col < subdivisionsX; col++) {
  37364. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37365. indices.push(col + 1 + row * (subdivisionsX + 1));
  37366. indices.push(col + row * (subdivisionsX + 1));
  37367. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37368. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37369. indices.push(col + row * (subdivisionsX + 1));
  37370. }
  37371. }
  37372. // Result
  37373. var vertexData = new VertexData();
  37374. vertexData.indices = indices;
  37375. vertexData.positions = positions;
  37376. vertexData.normals = normals;
  37377. vertexData.uvs = uvs;
  37378. return vertexData;
  37379. };
  37380. /**
  37381. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37382. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37383. * * xmin the ground minimum X coordinate, optional, default -1
  37384. * * zmin the ground minimum Z coordinate, optional, default -1
  37385. * * xmax the ground maximum X coordinate, optional, default 1
  37386. * * zmax the ground maximum Z coordinate, optional, default 1
  37387. * * 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}
  37388. * * 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}
  37389. * @returns the VertexData of the TiledGround
  37390. */
  37391. VertexData.CreateTiledGround = function (options) {
  37392. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37393. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37394. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37395. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37396. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37397. var precision = options.precision || { w: 1, h: 1 };
  37398. var indices = new Array();
  37399. var positions = new Array();
  37400. var normals = new Array();
  37401. var uvs = new Array();
  37402. var row, col, tileRow, tileCol;
  37403. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37404. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37405. precision.w = (precision.w < 1) ? 1 : precision.w;
  37406. precision.h = (precision.h < 1) ? 1 : precision.h;
  37407. var tileSize = {
  37408. 'w': (xmax - xmin) / subdivisions.w,
  37409. 'h': (zmax - zmin) / subdivisions.h
  37410. };
  37411. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37412. // Indices
  37413. var base = positions.length / 3;
  37414. var rowLength = precision.w + 1;
  37415. for (row = 0; row < precision.h; row++) {
  37416. for (col = 0; col < precision.w; col++) {
  37417. var square = [
  37418. base + col + row * rowLength,
  37419. base + (col + 1) + row * rowLength,
  37420. base + (col + 1) + (row + 1) * rowLength,
  37421. base + col + (row + 1) * rowLength
  37422. ];
  37423. indices.push(square[1]);
  37424. indices.push(square[2]);
  37425. indices.push(square[3]);
  37426. indices.push(square[0]);
  37427. indices.push(square[1]);
  37428. indices.push(square[3]);
  37429. }
  37430. }
  37431. // Position, normals and uvs
  37432. var position = BABYLON.Vector3.Zero();
  37433. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37434. for (row = 0; row <= precision.h; row++) {
  37435. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37436. for (col = 0; col <= precision.w; col++) {
  37437. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37438. position.y = 0;
  37439. positions.push(position.x, position.y, position.z);
  37440. normals.push(normal.x, normal.y, normal.z);
  37441. uvs.push(col / precision.w, row / precision.h);
  37442. }
  37443. }
  37444. }
  37445. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37446. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37447. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37448. }
  37449. }
  37450. // Result
  37451. var vertexData = new VertexData();
  37452. vertexData.indices = indices;
  37453. vertexData.positions = positions;
  37454. vertexData.normals = normals;
  37455. vertexData.uvs = uvs;
  37456. return vertexData;
  37457. };
  37458. /**
  37459. * Creates the VertexData of the Ground designed from a heightmap
  37460. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37461. * * width the width (x direction) of the ground
  37462. * * height the height (z direction) of the ground
  37463. * * subdivisions the number of subdivisions per side
  37464. * * minHeight the minimum altitude on the ground, optional, default 0
  37465. * * maxHeight the maximum altitude on the ground, optional default 1
  37466. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37467. * * buffer the array holding the image color data
  37468. * * bufferWidth the width of image
  37469. * * bufferHeight the height of image
  37470. * @returns the VertexData of the Ground designed from a heightmap
  37471. */
  37472. VertexData.CreateGroundFromHeightMap = function (options) {
  37473. var indices = [];
  37474. var positions = [];
  37475. var normals = [];
  37476. var uvs = [];
  37477. var row, col;
  37478. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37479. // Vertices
  37480. for (row = 0; row <= options.subdivisions; row++) {
  37481. for (col = 0; col <= options.subdivisions; col++) {
  37482. 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));
  37483. // Compute height
  37484. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37485. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37486. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37487. var r = options.buffer[pos] / 255.0;
  37488. var g = options.buffer[pos + 1] / 255.0;
  37489. var b = options.buffer[pos + 2] / 255.0;
  37490. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37491. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37492. // Add vertex
  37493. positions.push(position.x, position.y, position.z);
  37494. normals.push(0, 0, 0);
  37495. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37496. }
  37497. }
  37498. // Indices
  37499. for (row = 0; row < options.subdivisions; row++) {
  37500. for (col = 0; col < options.subdivisions; col++) {
  37501. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37502. indices.push(col + 1 + row * (options.subdivisions + 1));
  37503. indices.push(col + row * (options.subdivisions + 1));
  37504. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37505. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37506. indices.push(col + row * (options.subdivisions + 1));
  37507. }
  37508. }
  37509. // Normals
  37510. VertexData.ComputeNormals(positions, indices, normals);
  37511. // Result
  37512. var vertexData = new VertexData();
  37513. vertexData.indices = indices;
  37514. vertexData.positions = positions;
  37515. vertexData.normals = normals;
  37516. vertexData.uvs = uvs;
  37517. return vertexData;
  37518. };
  37519. /**
  37520. * Creates the VertexData for a Plane
  37521. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37522. * * size sets the width and height of the plane to the value of size, optional default 1
  37523. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37524. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37525. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37526. * * 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)
  37527. * * 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)
  37528. * @returns the VertexData of the box
  37529. */
  37530. VertexData.CreatePlane = function (options) {
  37531. var indices = [];
  37532. var positions = [];
  37533. var normals = [];
  37534. var uvs = [];
  37535. var width = options.width || options.size || 1;
  37536. var height = options.height || options.size || 1;
  37537. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37538. // Vertices
  37539. var halfWidth = width / 2.0;
  37540. var halfHeight = height / 2.0;
  37541. positions.push(-halfWidth, -halfHeight, 0);
  37542. normals.push(0, 0, -1.0);
  37543. uvs.push(0.0, 0.0);
  37544. positions.push(halfWidth, -halfHeight, 0);
  37545. normals.push(0, 0, -1.0);
  37546. uvs.push(1.0, 0.0);
  37547. positions.push(halfWidth, halfHeight, 0);
  37548. normals.push(0, 0, -1.0);
  37549. uvs.push(1.0, 1.0);
  37550. positions.push(-halfWidth, halfHeight, 0);
  37551. normals.push(0, 0, -1.0);
  37552. uvs.push(0.0, 1.0);
  37553. // Indices
  37554. indices.push(0);
  37555. indices.push(1);
  37556. indices.push(2);
  37557. indices.push(0);
  37558. indices.push(2);
  37559. indices.push(3);
  37560. // Sides
  37561. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37562. // Result
  37563. var vertexData = new VertexData();
  37564. vertexData.indices = indices;
  37565. vertexData.positions = positions;
  37566. vertexData.normals = normals;
  37567. vertexData.uvs = uvs;
  37568. return vertexData;
  37569. };
  37570. /**
  37571. * Creates the VertexData of the Disc or regular Polygon
  37572. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37573. * * radius the radius of the disc, optional default 0.5
  37574. * * tessellation the number of polygon sides, optional, default 64
  37575. * * 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
  37576. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37577. * * 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)
  37578. * * 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)
  37579. * @returns the VertexData of the box
  37580. */
  37581. VertexData.CreateDisc = function (options) {
  37582. var positions = new Array();
  37583. var indices = new Array();
  37584. var normals = new Array();
  37585. var uvs = new Array();
  37586. var radius = options.radius || 0.5;
  37587. var tessellation = options.tessellation || 64;
  37588. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37589. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37590. // positions and uvs
  37591. positions.push(0, 0, 0); // disc center first
  37592. uvs.push(0.5, 0.5);
  37593. var theta = Math.PI * 2 * arc;
  37594. var step = theta / tessellation;
  37595. for (var a = 0; a < theta; a += step) {
  37596. var x = Math.cos(a);
  37597. var y = Math.sin(a);
  37598. var u = (x + 1) / 2;
  37599. var v = (1 - y) / 2;
  37600. positions.push(radius * x, radius * y, 0);
  37601. uvs.push(u, v);
  37602. }
  37603. if (arc === 1) {
  37604. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37605. uvs.push(uvs[2], uvs[3]);
  37606. }
  37607. //indices
  37608. var vertexNb = positions.length / 3;
  37609. for (var i = 1; i < vertexNb - 1; i++) {
  37610. indices.push(i + 1, 0, i);
  37611. }
  37612. // result
  37613. VertexData.ComputeNormals(positions, indices, normals);
  37614. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37615. var vertexData = new VertexData();
  37616. vertexData.indices = indices;
  37617. vertexData.positions = positions;
  37618. vertexData.normals = normals;
  37619. vertexData.uvs = uvs;
  37620. return vertexData;
  37621. };
  37622. /**
  37623. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37624. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37625. * @param polygon a mesh built from polygonTriangulation.build()
  37626. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37627. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37628. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37629. * @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)
  37630. * @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)
  37631. * @returns the VertexData of the Polygon
  37632. */
  37633. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37634. var faceUV = fUV || new Array(3);
  37635. var faceColors = fColors;
  37636. var colors = [];
  37637. // default face colors and UV if undefined
  37638. for (var f = 0; f < 3; f++) {
  37639. if (faceUV[f] === undefined) {
  37640. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37641. }
  37642. if (faceColors && faceColors[f] === undefined) {
  37643. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37644. }
  37645. }
  37646. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37647. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37648. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37649. var indices = polygon.getIndices();
  37650. // set face colours and textures
  37651. var idx = 0;
  37652. var face = 0;
  37653. for (var index = 0; index < normals.length; index += 3) {
  37654. //Edge Face no. 1
  37655. if (Math.abs(normals[index + 1]) < 0.001) {
  37656. face = 1;
  37657. }
  37658. //Top Face no. 0
  37659. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37660. face = 0;
  37661. }
  37662. //Bottom Face no. 2
  37663. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37664. face = 2;
  37665. }
  37666. idx = index / 3;
  37667. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37668. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37669. if (faceColors) {
  37670. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37671. }
  37672. }
  37673. // sides
  37674. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37675. // Result
  37676. var vertexData = new VertexData();
  37677. vertexData.indices = indices;
  37678. vertexData.positions = positions;
  37679. vertexData.normals = normals;
  37680. vertexData.uvs = uvs;
  37681. if (faceColors) {
  37682. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37683. vertexData.colors = totalColors;
  37684. }
  37685. return vertexData;
  37686. };
  37687. /**
  37688. * Creates the VertexData of the IcoSphere
  37689. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37690. * * radius the radius of the IcoSphere, optional default 1
  37691. * * radiusX allows stretching in the x direction, optional, default radius
  37692. * * radiusY allows stretching in the y direction, optional, default radius
  37693. * * radiusZ allows stretching in the z direction, optional, default radius
  37694. * * flat when true creates a flat shaded mesh, optional, default true
  37695. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37696. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37697. * * 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)
  37698. * * 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)
  37699. * @returns the VertexData of the IcoSphere
  37700. */
  37701. VertexData.CreateIcoSphere = function (options) {
  37702. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37703. var radius = options.radius || 1;
  37704. var flat = (options.flat === undefined) ? true : options.flat;
  37705. var subdivisions = options.subdivisions || 4;
  37706. var radiusX = options.radiusX || radius;
  37707. var radiusY = options.radiusY || radius;
  37708. var radiusZ = options.radiusZ || radius;
  37709. var t = (1 + Math.sqrt(5)) / 2;
  37710. // 12 vertex x,y,z
  37711. var ico_vertices = [
  37712. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37713. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37714. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37715. ];
  37716. // index of 3 vertex makes a face of icopshere
  37717. var ico_indices = [
  37718. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37719. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37720. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37721. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37722. ];
  37723. // vertex for uv have aliased position, not for UV
  37724. var vertices_unalias_id = [
  37725. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37726. // vertex alias
  37727. 0,
  37728. 2,
  37729. 3,
  37730. 3,
  37731. 3,
  37732. 4,
  37733. 7,
  37734. 8,
  37735. 9,
  37736. 9,
  37737. 10,
  37738. 11 // 23: B + 12
  37739. ];
  37740. // uv as integer step (not pixels !)
  37741. var ico_vertexuv = [
  37742. 5, 1, 3, 1, 6, 4, 0, 0,
  37743. 5, 3, 4, 2, 2, 2, 4, 0,
  37744. 2, 0, 1, 1, 6, 0, 6, 2,
  37745. // vertex alias (for same vertex on different faces)
  37746. 0, 4,
  37747. 3, 3,
  37748. 4, 4,
  37749. 3, 1,
  37750. 4, 2,
  37751. 4, 4,
  37752. 0, 2,
  37753. 1, 1,
  37754. 2, 2,
  37755. 3, 3,
  37756. 1, 3,
  37757. 2, 4 // 23: B + 12
  37758. ];
  37759. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37760. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37761. // First island of uv mapping
  37762. // v = 4h 3+ 2
  37763. // v = 3h 9+ 4
  37764. // v = 2h 9+ 5 B
  37765. // v = 1h 9 1 0
  37766. // v = 0h 3 8 7 A
  37767. // u = 0 1 2 3 4 5 6 *a
  37768. // Second island of uv mapping
  37769. // v = 4h 0+ B+ 4+
  37770. // v = 3h A+ 2+
  37771. // v = 2h 7+ 6 3+
  37772. // v = 1h 8+ 3+
  37773. // v = 0h
  37774. // u = 0 1 2 3 4 5 6 *a
  37775. // Face layout on texture UV mapping
  37776. // ============
  37777. // \ 4 /\ 16 / ======
  37778. // \ / \ / /\ 11 /
  37779. // \/ 7 \/ / \ /
  37780. // ======= / 10 \/
  37781. // /\ 17 /\ =======
  37782. // / \ / \ \ 15 /\
  37783. // / 8 \/ 12 \ \ / \
  37784. // ============ \/ 6 \
  37785. // \ 18 /\ ============
  37786. // \ / \ \ 5 /\ 0 /
  37787. // \/ 13 \ \ / \ /
  37788. // ======= \/ 1 \/
  37789. // =============
  37790. // /\ 19 /\ 2 /\
  37791. // / \ / \ / \
  37792. // / 14 \/ 9 \/ 3 \
  37793. // ===================
  37794. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37795. var ustep = 138 / 1024;
  37796. var vstep = 239 / 1024;
  37797. var uoffset = 60 / 1024;
  37798. var voffset = 26 / 1024;
  37799. // Second island should have margin, not to touch the first island
  37800. // avoid any borderline artefact in pixel rounding
  37801. var island_u_offset = -40 / 1024;
  37802. var island_v_offset = +20 / 1024;
  37803. // face is either island 0 or 1 :
  37804. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37805. var island = [
  37806. 0, 0, 0, 0, 1,
  37807. 0, 0, 1, 1, 0,
  37808. 0, 0, 1, 1, 0,
  37809. 0, 1, 1, 1, 0 // 15 - 19
  37810. ];
  37811. var indices = new Array();
  37812. var positions = new Array();
  37813. var normals = new Array();
  37814. var uvs = new Array();
  37815. var current_indice = 0;
  37816. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37817. var face_vertex_pos = new Array(3);
  37818. var face_vertex_uv = new Array(3);
  37819. var v012;
  37820. for (v012 = 0; v012 < 3; v012++) {
  37821. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37822. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37823. }
  37824. // create all with normals
  37825. for (var face = 0; face < 20; face++) {
  37826. // 3 vertex per face
  37827. for (v012 = 0; v012 < 3; v012++) {
  37828. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37829. var v_id = ico_indices[3 * face + v012];
  37830. // vertex have 3D position (x,y,z)
  37831. 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]);
  37832. // Normalize to get normal, then scale to radius
  37833. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37834. // uv Coordinates from vertex ID
  37835. 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);
  37836. }
  37837. // Subdivide the face (interpolate pos, norm, uv)
  37838. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37839. // - norm is linear interpolation of vertex corner normal
  37840. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37841. // - uv is linear interpolation
  37842. //
  37843. // Topology is as below for sub-divide by 2
  37844. // vertex shown as v0,v1,v2
  37845. // interp index is i1 to progress in range [v0,v1[
  37846. // interp index is i2 to progress in range [v0,v2[
  37847. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37848. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37849. //
  37850. //
  37851. // i2 v2
  37852. // ^ ^
  37853. // / / \
  37854. // / / \
  37855. // / / \
  37856. // / / (0,1) \
  37857. // / #---------\
  37858. // / / \ (0,0)'/ \
  37859. // / / \ / \
  37860. // / / \ / \
  37861. // / / (0,0) \ / (1,0) \
  37862. // / #---------#---------\
  37863. // v0 v1
  37864. //
  37865. // --------------------> i1
  37866. //
  37867. // interp of (i1,i2):
  37868. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37869. // along i1 : lerp(x0,x1, i1/(S-i2))
  37870. //
  37871. // centroid of triangle is needed to get help normal computation
  37872. // (c1,c2) are used for centroid location
  37873. var interp_vertex = function (i1, i2, c1, c2) {
  37874. // vertex is interpolated from
  37875. // - face_vertex_pos[0..2]
  37876. // - face_vertex_uv[0..2]
  37877. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37878. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37879. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37880. pos_interp.normalize();
  37881. var vertex_normal;
  37882. if (flat) {
  37883. // in flat mode, recalculate normal as face centroid normal
  37884. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37885. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37886. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37887. }
  37888. else {
  37889. // in smooth mode, recalculate normal from each single vertex position
  37890. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37891. }
  37892. // Vertex normal need correction due to X,Y,Z radius scaling
  37893. vertex_normal.x /= radiusX;
  37894. vertex_normal.y /= radiusY;
  37895. vertex_normal.z /= radiusZ;
  37896. vertex_normal.normalize();
  37897. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37898. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37899. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37900. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37901. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37902. uvs.push(uv_interp.x, uv_interp.y);
  37903. // push each vertex has member of a face
  37904. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37905. indices.push(current_indice);
  37906. current_indice++;
  37907. };
  37908. for (var i2 = 0; i2 < subdivisions; i2++) {
  37909. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37910. // face : (i1,i2) for /\ :
  37911. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37912. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37913. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37914. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37915. if (i1 + i2 + 1 < subdivisions) {
  37916. // face : (i1,i2)' for \/ :
  37917. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37918. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37919. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37920. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37921. }
  37922. }
  37923. }
  37924. }
  37925. // Sides
  37926. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37927. // Result
  37928. var vertexData = new VertexData();
  37929. vertexData.indices = indices;
  37930. vertexData.positions = positions;
  37931. vertexData.normals = normals;
  37932. vertexData.uvs = uvs;
  37933. return vertexData;
  37934. };
  37935. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37936. /**
  37937. * Creates the VertexData for a Polyhedron
  37938. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37939. * * type provided types are:
  37940. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37941. * * 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)
  37942. * * size the size of the IcoSphere, optional default 1
  37943. * * sizeX allows stretching in the x direction, optional, default size
  37944. * * sizeY allows stretching in the y direction, optional, default size
  37945. * * sizeZ allows stretching in the z direction, optional, default size
  37946. * * 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
  37947. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37948. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37949. * * flat when true creates a flat shaded mesh, optional, default true
  37950. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37951. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37952. * * 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)
  37953. * * 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)
  37954. * @returns the VertexData of the Polyhedron
  37955. */
  37956. VertexData.CreatePolyhedron = function (options) {
  37957. // provided polyhedron types :
  37958. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37959. // 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)
  37960. var polyhedra = [];
  37961. 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]] };
  37962. 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]] };
  37963. polyhedra[2] = {
  37964. 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]],
  37965. 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]]
  37966. };
  37967. polyhedra[3] = {
  37968. 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]],
  37969. 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]]
  37970. };
  37971. polyhedra[4] = {
  37972. 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]],
  37973. 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]]
  37974. };
  37975. 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]] };
  37976. 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]] };
  37977. 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]] };
  37978. 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]] };
  37979. 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]] };
  37980. 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]] };
  37981. 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]] };
  37982. 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]] };
  37983. 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]] };
  37984. polyhedra[14] = {
  37985. 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]],
  37986. 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]]
  37987. };
  37988. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37989. var size = options.size;
  37990. var sizeX = options.sizeX || size || 1;
  37991. var sizeY = options.sizeY || size || 1;
  37992. var sizeZ = options.sizeZ || size || 1;
  37993. var data = options.custom || polyhedra[type];
  37994. var nbfaces = data.face.length;
  37995. var faceUV = options.faceUV || new Array(nbfaces);
  37996. var faceColors = options.faceColors;
  37997. var flat = (options.flat === undefined) ? true : options.flat;
  37998. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37999. var positions = new Array();
  38000. var indices = new Array();
  38001. var normals = new Array();
  38002. var uvs = new Array();
  38003. var colors = new Array();
  38004. var index = 0;
  38005. var faceIdx = 0; // face cursor in the array "indexes"
  38006. var indexes = new Array();
  38007. var i = 0;
  38008. var f = 0;
  38009. var u, v, ang, x, y, tmp;
  38010. // default face colors and UV if undefined
  38011. if (flat) {
  38012. for (f = 0; f < nbfaces; f++) {
  38013. if (faceColors && faceColors[f] === undefined) {
  38014. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38015. }
  38016. if (faceUV && faceUV[f] === undefined) {
  38017. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38018. }
  38019. }
  38020. }
  38021. if (!flat) {
  38022. for (i = 0; i < data.vertex.length; i++) {
  38023. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38024. uvs.push(0, 0);
  38025. }
  38026. for (f = 0; f < nbfaces; f++) {
  38027. for (i = 0; i < data.face[f].length - 2; i++) {
  38028. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38029. }
  38030. }
  38031. }
  38032. else {
  38033. for (f = 0; f < nbfaces; f++) {
  38034. var fl = data.face[f].length; // number of vertices of the current face
  38035. ang = 2 * Math.PI / fl;
  38036. x = 0.5 * Math.tan(ang / 2);
  38037. y = 0.5;
  38038. // positions, uvs, colors
  38039. for (i = 0; i < fl; i++) {
  38040. // positions
  38041. 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);
  38042. indexes.push(index);
  38043. index++;
  38044. // uvs
  38045. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38046. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38047. uvs.push(u, v);
  38048. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38049. y = x * Math.sin(ang) + y * Math.cos(ang);
  38050. x = tmp;
  38051. // colors
  38052. if (faceColors) {
  38053. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38054. }
  38055. }
  38056. // indices from indexes
  38057. for (i = 0; i < fl - 2; i++) {
  38058. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38059. }
  38060. faceIdx += fl;
  38061. }
  38062. }
  38063. VertexData.ComputeNormals(positions, indices, normals);
  38064. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38065. var vertexData = new VertexData();
  38066. vertexData.positions = positions;
  38067. vertexData.indices = indices;
  38068. vertexData.normals = normals;
  38069. vertexData.uvs = uvs;
  38070. if (faceColors && flat) {
  38071. vertexData.colors = colors;
  38072. }
  38073. return vertexData;
  38074. };
  38075. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38076. /**
  38077. * Creates the VertexData for a TorusKnot
  38078. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38079. * * radius the radius of the torus knot, optional, default 2
  38080. * * tube the thickness of the tube, optional, default 0.5
  38081. * * radialSegments the number of sides on each tube segments, optional, default 32
  38082. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38083. * * p the number of windings around the z axis, optional, default 2
  38084. * * q the number of windings around the x axis, optional, default 3
  38085. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38086. * * 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)
  38087. * * 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)
  38088. * @returns the VertexData of the Torus Knot
  38089. */
  38090. VertexData.CreateTorusKnot = function (options) {
  38091. var indices = new Array();
  38092. var positions = new Array();
  38093. var normals = new Array();
  38094. var uvs = new Array();
  38095. var radius = options.radius || 2;
  38096. var tube = options.tube || 0.5;
  38097. var radialSegments = options.radialSegments || 32;
  38098. var tubularSegments = options.tubularSegments || 32;
  38099. var p = options.p || 2;
  38100. var q = options.q || 3;
  38101. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38102. // Helper
  38103. var getPos = function (angle) {
  38104. var cu = Math.cos(angle);
  38105. var su = Math.sin(angle);
  38106. var quOverP = q / p * angle;
  38107. var cs = Math.cos(quOverP);
  38108. var tx = radius * (2 + cs) * 0.5 * cu;
  38109. var ty = radius * (2 + cs) * su * 0.5;
  38110. var tz = radius * Math.sin(quOverP) * 0.5;
  38111. return new BABYLON.Vector3(tx, ty, tz);
  38112. };
  38113. // Vertices
  38114. var i;
  38115. var j;
  38116. for (i = 0; i <= radialSegments; i++) {
  38117. var modI = i % radialSegments;
  38118. var u = modI / radialSegments * 2 * p * Math.PI;
  38119. var p1 = getPos(u);
  38120. var p2 = getPos(u + 0.01);
  38121. var tang = p2.subtract(p1);
  38122. var n = p2.add(p1);
  38123. var bitan = BABYLON.Vector3.Cross(tang, n);
  38124. n = BABYLON.Vector3.Cross(bitan, tang);
  38125. bitan.normalize();
  38126. n.normalize();
  38127. for (j = 0; j < tubularSegments; j++) {
  38128. var modJ = j % tubularSegments;
  38129. var v = modJ / tubularSegments * 2 * Math.PI;
  38130. var cx = -tube * Math.cos(v);
  38131. var cy = tube * Math.sin(v);
  38132. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38133. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38134. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38135. uvs.push(i / radialSegments);
  38136. uvs.push(j / tubularSegments);
  38137. }
  38138. }
  38139. for (i = 0; i < radialSegments; i++) {
  38140. for (j = 0; j < tubularSegments; j++) {
  38141. var jNext = (j + 1) % tubularSegments;
  38142. var a = i * tubularSegments + j;
  38143. var b = (i + 1) * tubularSegments + j;
  38144. var c = (i + 1) * tubularSegments + jNext;
  38145. var d = i * tubularSegments + jNext;
  38146. indices.push(d);
  38147. indices.push(b);
  38148. indices.push(a);
  38149. indices.push(d);
  38150. indices.push(c);
  38151. indices.push(b);
  38152. }
  38153. }
  38154. // Normals
  38155. VertexData.ComputeNormals(positions, indices, normals);
  38156. // Sides
  38157. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38158. // Result
  38159. var vertexData = new VertexData();
  38160. vertexData.indices = indices;
  38161. vertexData.positions = positions;
  38162. vertexData.normals = normals;
  38163. vertexData.uvs = uvs;
  38164. return vertexData;
  38165. };
  38166. // Tools
  38167. /**
  38168. * Compute normals for given positions and indices
  38169. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38170. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38171. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38172. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38173. * * facetNormals : optional array of facet normals (vector3)
  38174. * * facetPositions : optional array of facet positions (vector3)
  38175. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38176. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38177. * * bInfo : optional bounding info, required for facetPartitioning computation
  38178. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38179. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38180. * * useRightHandedSystem: optional boolean to for right handed system computation
  38181. * * depthSort : optional boolean to enable the facet depth sort computation
  38182. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38183. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38184. */
  38185. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38186. // temporary scalar variables
  38187. var index = 0; // facet index
  38188. var p1p2x = 0.0; // p1p2 vector x coordinate
  38189. var p1p2y = 0.0; // p1p2 vector y coordinate
  38190. var p1p2z = 0.0; // p1p2 vector z coordinate
  38191. var p3p2x = 0.0; // p3p2 vector x coordinate
  38192. var p3p2y = 0.0; // p3p2 vector y coordinate
  38193. var p3p2z = 0.0; // p3p2 vector z coordinate
  38194. var faceNormalx = 0.0; // facet normal x coordinate
  38195. var faceNormaly = 0.0; // facet normal y coordinate
  38196. var faceNormalz = 0.0; // facet normal z coordinate
  38197. var length = 0.0; // facet normal length before normalization
  38198. var v1x = 0; // vector1 x index in the positions array
  38199. var v1y = 0; // vector1 y index in the positions array
  38200. var v1z = 0; // vector1 z index in the positions array
  38201. var v2x = 0; // vector2 x index in the positions array
  38202. var v2y = 0; // vector2 y index in the positions array
  38203. var v2z = 0; // vector2 z index in the positions array
  38204. var v3x = 0; // vector3 x index in the positions array
  38205. var v3y = 0; // vector3 y index in the positions array
  38206. var v3z = 0; // vector3 z index in the positions array
  38207. var computeFacetNormals = false;
  38208. var computeFacetPositions = false;
  38209. var computeFacetPartitioning = false;
  38210. var computeDepthSort = false;
  38211. var faceNormalSign = 1;
  38212. var ratio = 0;
  38213. var distanceTo = null;
  38214. if (options) {
  38215. computeFacetNormals = (options.facetNormals) ? true : false;
  38216. computeFacetPositions = (options.facetPositions) ? true : false;
  38217. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38218. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38219. ratio = options.ratio || 0;
  38220. computeDepthSort = (options.depthSort) ? true : false;
  38221. distanceTo = (options.distanceTo);
  38222. if (computeDepthSort) {
  38223. if (distanceTo === undefined) {
  38224. distanceTo = BABYLON.Vector3.Zero();
  38225. }
  38226. var depthSortedFacets = options.depthSortedFacets;
  38227. }
  38228. }
  38229. // facetPartitioning reinit if needed
  38230. var xSubRatio = 0;
  38231. var ySubRatio = 0;
  38232. var zSubRatio = 0;
  38233. var subSq = 0;
  38234. if (computeFacetPartitioning && options && options.bbSize) {
  38235. var ox = 0; // X partitioning index for facet position
  38236. var oy = 0; // Y partinioning index for facet position
  38237. var oz = 0; // Z partinioning index for facet position
  38238. var b1x = 0; // X partitioning index for facet v1 vertex
  38239. var b1y = 0; // Y partitioning index for facet v1 vertex
  38240. var b1z = 0; // z partitioning index for facet v1 vertex
  38241. var b2x = 0; // X partitioning index for facet v2 vertex
  38242. var b2y = 0; // Y partitioning index for facet v2 vertex
  38243. var b2z = 0; // Z partitioning index for facet v2 vertex
  38244. var b3x = 0; // X partitioning index for facet v3 vertex
  38245. var b3y = 0; // Y partitioning index for facet v3 vertex
  38246. var b3z = 0; // Z partitioning index for facet v3 vertex
  38247. var block_idx_o = 0; // facet barycenter block index
  38248. var block_idx_v1 = 0; // v1 vertex block index
  38249. var block_idx_v2 = 0; // v2 vertex block index
  38250. var block_idx_v3 = 0; // v3 vertex block index
  38251. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38252. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38253. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38254. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38255. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38256. subSq = options.subDiv.max * options.subDiv.max;
  38257. options.facetPartitioning.length = 0;
  38258. }
  38259. // reset the normals
  38260. for (index = 0; index < positions.length; index++) {
  38261. normals[index] = 0.0;
  38262. }
  38263. // Loop : 1 indice triplet = 1 facet
  38264. var nbFaces = (indices.length / 3) | 0;
  38265. for (index = 0; index < nbFaces; index++) {
  38266. // get the indexes of the coordinates of each vertex of the facet
  38267. v1x = indices[index * 3] * 3;
  38268. v1y = v1x + 1;
  38269. v1z = v1x + 2;
  38270. v2x = indices[index * 3 + 1] * 3;
  38271. v2y = v2x + 1;
  38272. v2z = v2x + 2;
  38273. v3x = indices[index * 3 + 2] * 3;
  38274. v3y = v3x + 1;
  38275. v3z = v3x + 2;
  38276. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38277. p1p2y = positions[v1y] - positions[v2y];
  38278. p1p2z = positions[v1z] - positions[v2z];
  38279. p3p2x = positions[v3x] - positions[v2x];
  38280. p3p2y = positions[v3y] - positions[v2y];
  38281. p3p2z = positions[v3z] - positions[v2z];
  38282. // compute the face normal with the cross product
  38283. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38284. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38285. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38286. // normalize this normal and store it in the array facetData
  38287. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38288. length = (length === 0) ? 1.0 : length;
  38289. faceNormalx /= length;
  38290. faceNormaly /= length;
  38291. faceNormalz /= length;
  38292. if (computeFacetNormals && options) {
  38293. options.facetNormals[index].x = faceNormalx;
  38294. options.facetNormals[index].y = faceNormaly;
  38295. options.facetNormals[index].z = faceNormalz;
  38296. }
  38297. if (computeFacetPositions && options) {
  38298. // compute and the facet barycenter coordinates in the array facetPositions
  38299. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38300. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38301. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38302. }
  38303. if (computeFacetPartitioning && options) {
  38304. // store the facet indexes in arrays in the main facetPartitioning array :
  38305. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38306. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38307. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38308. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38309. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38310. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38311. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38312. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38313. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38314. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38315. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38316. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38317. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38318. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38319. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38320. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38321. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38322. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38323. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38324. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38325. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38326. // push each facet index in each block containing the vertex
  38327. options.facetPartitioning[block_idx_v1].push(index);
  38328. if (block_idx_v2 != block_idx_v1) {
  38329. options.facetPartitioning[block_idx_v2].push(index);
  38330. }
  38331. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38332. options.facetPartitioning[block_idx_v3].push(index);
  38333. }
  38334. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38335. options.facetPartitioning[block_idx_o].push(index);
  38336. }
  38337. }
  38338. if (computeDepthSort && options && options.facetPositions) {
  38339. var dsf = depthSortedFacets[index];
  38340. dsf.ind = index * 3;
  38341. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38342. }
  38343. // compute the normals anyway
  38344. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38345. normals[v1y] += faceNormaly;
  38346. normals[v1z] += faceNormalz;
  38347. normals[v2x] += faceNormalx;
  38348. normals[v2y] += faceNormaly;
  38349. normals[v2z] += faceNormalz;
  38350. normals[v3x] += faceNormalx;
  38351. normals[v3y] += faceNormaly;
  38352. normals[v3z] += faceNormalz;
  38353. }
  38354. // last normalization of each normal
  38355. for (index = 0; index < normals.length / 3; index++) {
  38356. faceNormalx = normals[index * 3];
  38357. faceNormaly = normals[index * 3 + 1];
  38358. faceNormalz = normals[index * 3 + 2];
  38359. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38360. length = (length === 0) ? 1.0 : length;
  38361. faceNormalx /= length;
  38362. faceNormaly /= length;
  38363. faceNormalz /= length;
  38364. normals[index * 3] = faceNormalx;
  38365. normals[index * 3 + 1] = faceNormaly;
  38366. normals[index * 3 + 2] = faceNormalz;
  38367. }
  38368. };
  38369. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38370. var li = indices.length;
  38371. var ln = normals.length;
  38372. var i;
  38373. var n;
  38374. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38375. switch (sideOrientation) {
  38376. case BABYLON.Mesh.FRONTSIDE:
  38377. // nothing changed
  38378. break;
  38379. case BABYLON.Mesh.BACKSIDE:
  38380. var tmp;
  38381. // indices
  38382. for (i = 0; i < li; i += 3) {
  38383. tmp = indices[i];
  38384. indices[i] = indices[i + 2];
  38385. indices[i + 2] = tmp;
  38386. }
  38387. // normals
  38388. for (n = 0; n < ln; n++) {
  38389. normals[n] = -normals[n];
  38390. }
  38391. break;
  38392. case BABYLON.Mesh.DOUBLESIDE:
  38393. // positions
  38394. var lp = positions.length;
  38395. var l = lp / 3;
  38396. for (var p = 0; p < lp; p++) {
  38397. positions[lp + p] = positions[p];
  38398. }
  38399. // indices
  38400. for (i = 0; i < li; i += 3) {
  38401. indices[i + li] = indices[i + 2] + l;
  38402. indices[i + 1 + li] = indices[i + 1] + l;
  38403. indices[i + 2 + li] = indices[i] + l;
  38404. }
  38405. // normals
  38406. for (n = 0; n < ln; n++) {
  38407. normals[ln + n] = -normals[n];
  38408. }
  38409. // uvs
  38410. var lu = uvs.length;
  38411. var u = 0;
  38412. for (u = 0; u < lu; u++) {
  38413. uvs[u + lu] = uvs[u];
  38414. }
  38415. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38416. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38417. u = 0;
  38418. for (i = 0; i < lu / 2; i++) {
  38419. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38420. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38421. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38422. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38423. u += 2;
  38424. }
  38425. break;
  38426. }
  38427. };
  38428. /**
  38429. * Applies VertexData created from the imported parameters to the geometry
  38430. * @param parsedVertexData the parsed data from an imported file
  38431. * @param geometry the geometry to apply the VertexData to
  38432. */
  38433. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38434. var vertexData = new VertexData();
  38435. // positions
  38436. var positions = parsedVertexData.positions;
  38437. if (positions) {
  38438. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38439. }
  38440. // normals
  38441. var normals = parsedVertexData.normals;
  38442. if (normals) {
  38443. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38444. }
  38445. // tangents
  38446. var tangents = parsedVertexData.tangents;
  38447. if (tangents) {
  38448. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38449. }
  38450. // uvs
  38451. var uvs = parsedVertexData.uvs;
  38452. if (uvs) {
  38453. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38454. }
  38455. // uv2s
  38456. var uv2s = parsedVertexData.uv2s;
  38457. if (uv2s) {
  38458. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38459. }
  38460. // uv3s
  38461. var uv3s = parsedVertexData.uv3s;
  38462. if (uv3s) {
  38463. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38464. }
  38465. // uv4s
  38466. var uv4s = parsedVertexData.uv4s;
  38467. if (uv4s) {
  38468. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38469. }
  38470. // uv5s
  38471. var uv5s = parsedVertexData.uv5s;
  38472. if (uv5s) {
  38473. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38474. }
  38475. // uv6s
  38476. var uv6s = parsedVertexData.uv6s;
  38477. if (uv6s) {
  38478. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38479. }
  38480. // colors
  38481. var colors = parsedVertexData.colors;
  38482. if (colors) {
  38483. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38484. }
  38485. // matricesIndices
  38486. var matricesIndices = parsedVertexData.matricesIndices;
  38487. if (matricesIndices) {
  38488. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38489. }
  38490. // matricesWeights
  38491. var matricesWeights = parsedVertexData.matricesWeights;
  38492. if (matricesWeights) {
  38493. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38494. }
  38495. // indices
  38496. var indices = parsedVertexData.indices;
  38497. if (indices) {
  38498. vertexData.indices = indices;
  38499. }
  38500. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38501. };
  38502. return VertexData;
  38503. }());
  38504. BABYLON.VertexData = VertexData;
  38505. })(BABYLON || (BABYLON = {}));
  38506. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38507. var BABYLON;
  38508. (function (BABYLON) {
  38509. /**
  38510. * Class used to store geometry data (vertex buffers + index buffer)
  38511. */
  38512. var Geometry = /** @class */ (function () {
  38513. /**
  38514. * Creates a new geometry
  38515. * @param id defines the unique ID
  38516. * @param scene defines the hosting scene
  38517. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38518. * @param updatable defines if geometry must be updatable (false by default)
  38519. * @param mesh defines the mesh that will be associated with the geometry
  38520. */
  38521. function Geometry(id, scene, vertexData, updatable, mesh) {
  38522. if (updatable === void 0) { updatable = false; }
  38523. if (mesh === void 0) { mesh = null; }
  38524. /**
  38525. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38526. */
  38527. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38528. this._totalVertices = 0;
  38529. this._isDisposed = false;
  38530. this._indexBufferIsUpdatable = false;
  38531. this.id = id;
  38532. this._engine = scene.getEngine();
  38533. this._meshes = [];
  38534. this._scene = scene;
  38535. //Init vertex buffer cache
  38536. this._vertexBuffers = {};
  38537. this._indices = [];
  38538. this._updatable = updatable;
  38539. // vertexData
  38540. if (vertexData) {
  38541. this.setAllVerticesData(vertexData, updatable);
  38542. }
  38543. else {
  38544. this._totalVertices = 0;
  38545. this._indices = [];
  38546. }
  38547. if (this._engine.getCaps().vertexArrayObject) {
  38548. this._vertexArrayObjects = {};
  38549. }
  38550. // applyToMesh
  38551. if (mesh) {
  38552. if (mesh.getClassName() === "LinesMesh") {
  38553. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38554. this._updateExtend();
  38555. }
  38556. this.applyToMesh(mesh);
  38557. mesh.computeWorldMatrix(true);
  38558. }
  38559. }
  38560. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38561. /**
  38562. * 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
  38563. */
  38564. get: function () {
  38565. return this._boundingBias;
  38566. },
  38567. /**
  38568. * 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
  38569. */
  38570. set: function (value) {
  38571. if (this._boundingBias && this._boundingBias.equals(value)) {
  38572. return;
  38573. }
  38574. this._boundingBias = value.clone();
  38575. this._updateBoundingInfo(true, null);
  38576. },
  38577. enumerable: true,
  38578. configurable: true
  38579. });
  38580. /**
  38581. * Static function used to attach a new empty geometry to a mesh
  38582. * @param mesh defines the mesh to attach the geometry to
  38583. * @returns the new {BABYLON.Geometry}
  38584. */
  38585. Geometry.CreateGeometryForMesh = function (mesh) {
  38586. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38587. geometry.applyToMesh(mesh);
  38588. return geometry;
  38589. };
  38590. Object.defineProperty(Geometry.prototype, "extend", {
  38591. /**
  38592. * Gets the current extend of the geometry
  38593. */
  38594. get: function () {
  38595. return this._extend;
  38596. },
  38597. enumerable: true,
  38598. configurable: true
  38599. });
  38600. /**
  38601. * Gets the hosting scene
  38602. * @returns the hosting {BABYLON.Scene}
  38603. */
  38604. Geometry.prototype.getScene = function () {
  38605. return this._scene;
  38606. };
  38607. /**
  38608. * Gets the hosting engine
  38609. * @returns the hosting {BABYLON.Engine}
  38610. */
  38611. Geometry.prototype.getEngine = function () {
  38612. return this._engine;
  38613. };
  38614. /**
  38615. * Defines if the geometry is ready to use
  38616. * @returns true if the geometry is ready to be used
  38617. */
  38618. Geometry.prototype.isReady = function () {
  38619. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38620. };
  38621. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38622. /**
  38623. * Gets a value indicating that the geometry should not be serialized
  38624. */
  38625. get: function () {
  38626. for (var index = 0; index < this._meshes.length; index++) {
  38627. if (!this._meshes[index].doNotSerialize) {
  38628. return false;
  38629. }
  38630. }
  38631. return true;
  38632. },
  38633. enumerable: true,
  38634. configurable: true
  38635. });
  38636. /** @hidden */
  38637. Geometry.prototype._rebuild = function () {
  38638. if (this._vertexArrayObjects) {
  38639. this._vertexArrayObjects = {};
  38640. }
  38641. // Index buffer
  38642. if (this._meshes.length !== 0 && this._indices) {
  38643. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38644. }
  38645. // Vertex buffers
  38646. for (var key in this._vertexBuffers) {
  38647. var vertexBuffer = this._vertexBuffers[key];
  38648. vertexBuffer._rebuild();
  38649. }
  38650. };
  38651. /**
  38652. * Affects all geometry data in one call
  38653. * @param vertexData defines the geometry data
  38654. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38655. */
  38656. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38657. vertexData.applyToGeometry(this, updatable);
  38658. this.notifyUpdate();
  38659. };
  38660. /**
  38661. * Set specific vertex data
  38662. * @param kind defines the data kind (Position, normal, etc...)
  38663. * @param data defines the vertex data to use
  38664. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38665. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38666. */
  38667. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38668. if (updatable === void 0) { updatable = false; }
  38669. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38670. this.setVerticesBuffer(buffer);
  38671. };
  38672. /**
  38673. * Removes a specific vertex data
  38674. * @param kind defines the data kind (Position, normal, etc...)
  38675. */
  38676. Geometry.prototype.removeVerticesData = function (kind) {
  38677. if (this._vertexBuffers[kind]) {
  38678. this._vertexBuffers[kind].dispose();
  38679. delete this._vertexBuffers[kind];
  38680. }
  38681. };
  38682. /**
  38683. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38684. * @param buffer defines the vertex buffer to use
  38685. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38686. */
  38687. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38688. if (totalVertices === void 0) { totalVertices = null; }
  38689. var kind = buffer.getKind();
  38690. if (this._vertexBuffers[kind]) {
  38691. this._vertexBuffers[kind].dispose();
  38692. }
  38693. this._vertexBuffers[kind] = buffer;
  38694. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38695. var data = buffer.getData();
  38696. if (totalVertices != null) {
  38697. this._totalVertices = totalVertices;
  38698. }
  38699. else {
  38700. if (data != null) {
  38701. this._totalVertices = data.length / (buffer.byteStride / 4);
  38702. }
  38703. }
  38704. this._updateExtend(data);
  38705. this._resetPointsArrayCache();
  38706. var meshes = this._meshes;
  38707. var numOfMeshes = meshes.length;
  38708. for (var index = 0; index < numOfMeshes; index++) {
  38709. var mesh = meshes[index];
  38710. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38711. mesh._createGlobalSubMesh(false);
  38712. mesh.computeWorldMatrix(true);
  38713. }
  38714. }
  38715. this.notifyUpdate(kind);
  38716. if (this._vertexArrayObjects) {
  38717. this._disposeVertexArrayObjects();
  38718. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38719. }
  38720. };
  38721. /**
  38722. * Update a specific vertex buffer
  38723. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38724. * It will do nothing if the buffer is not updatable
  38725. * @param kind defines the data kind (Position, normal, etc...)
  38726. * @param data defines the data to use
  38727. * @param offset defines the offset in the target buffer where to store the data
  38728. * @param useBytes set to true if the offset is in bytes
  38729. */
  38730. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38731. if (useBytes === void 0) { useBytes = false; }
  38732. var vertexBuffer = this.getVertexBuffer(kind);
  38733. if (!vertexBuffer) {
  38734. return;
  38735. }
  38736. vertexBuffer.updateDirectly(data, offset, useBytes);
  38737. this.notifyUpdate(kind);
  38738. };
  38739. /**
  38740. * Update a specific vertex buffer
  38741. * This function will create a new buffer if the current one is not updatable
  38742. * @param kind defines the data kind (Position, normal, etc...)
  38743. * @param data defines the data to use
  38744. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38745. */
  38746. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38747. if (updateExtends === void 0) { updateExtends = false; }
  38748. var vertexBuffer = this.getVertexBuffer(kind);
  38749. if (!vertexBuffer) {
  38750. return;
  38751. }
  38752. vertexBuffer.update(data);
  38753. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38754. this._updateBoundingInfo(updateExtends, data);
  38755. }
  38756. this.notifyUpdate(kind);
  38757. };
  38758. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38759. if (updateExtends) {
  38760. this._updateExtend(data);
  38761. }
  38762. var meshes = this._meshes;
  38763. var numOfMeshes = meshes.length;
  38764. this._resetPointsArrayCache();
  38765. for (var index = 0; index < numOfMeshes; index++) {
  38766. var mesh = meshes[index];
  38767. if (updateExtends) {
  38768. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38769. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38770. var subMesh = mesh.subMeshes[subIndex];
  38771. subMesh.refreshBoundingInfo();
  38772. }
  38773. }
  38774. }
  38775. };
  38776. /** @hidden */
  38777. Geometry.prototype._bind = function (effect, indexToBind) {
  38778. if (!effect) {
  38779. return;
  38780. }
  38781. if (indexToBind === undefined) {
  38782. indexToBind = this._indexBuffer;
  38783. }
  38784. var vbs = this.getVertexBuffers();
  38785. if (!vbs) {
  38786. return;
  38787. }
  38788. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38789. this._engine.bindBuffers(vbs, indexToBind, effect);
  38790. return;
  38791. }
  38792. // Using VAO
  38793. if (!this._vertexArrayObjects[effect.key]) {
  38794. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38795. }
  38796. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38797. };
  38798. /**
  38799. * Gets total number of vertices
  38800. * @returns the total number of vertices
  38801. */
  38802. Geometry.prototype.getTotalVertices = function () {
  38803. if (!this.isReady()) {
  38804. return 0;
  38805. }
  38806. return this._totalVertices;
  38807. };
  38808. /**
  38809. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38810. * @param kind defines the data kind (Position, normal, etc...)
  38811. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38812. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38813. * @returns a float array containing vertex data
  38814. */
  38815. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38816. var vertexBuffer = this.getVertexBuffer(kind);
  38817. if (!vertexBuffer) {
  38818. return null;
  38819. }
  38820. var data = vertexBuffer.getData();
  38821. if (!data) {
  38822. return null;
  38823. }
  38824. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38825. var count = this._totalVertices * vertexBuffer.getSize();
  38826. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38827. var copy_1 = new Array(count);
  38828. vertexBuffer.forEach(count, function (value, index) {
  38829. copy_1[index] = value;
  38830. });
  38831. return copy_1;
  38832. }
  38833. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38834. if (data instanceof Array) {
  38835. var offset = vertexBuffer.byteOffset / 4;
  38836. return BABYLON.Tools.Slice(data, offset, offset + count);
  38837. }
  38838. else if (data instanceof ArrayBuffer) {
  38839. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38840. }
  38841. else {
  38842. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38843. }
  38844. }
  38845. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38846. return BABYLON.Tools.Slice(data);
  38847. }
  38848. return data;
  38849. };
  38850. /**
  38851. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38852. * @param kind defines the data kind (Position, normal, etc...)
  38853. * @returns true if the vertex buffer with the specified kind is updatable
  38854. */
  38855. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38856. var vb = this._vertexBuffers[kind];
  38857. if (!vb) {
  38858. return false;
  38859. }
  38860. return vb.isUpdatable();
  38861. };
  38862. /**
  38863. * Gets a specific vertex buffer
  38864. * @param kind defines the data kind (Position, normal, etc...)
  38865. * @returns a {BABYLON.VertexBuffer}
  38866. */
  38867. Geometry.prototype.getVertexBuffer = function (kind) {
  38868. if (!this.isReady()) {
  38869. return null;
  38870. }
  38871. return this._vertexBuffers[kind];
  38872. };
  38873. /**
  38874. * Returns all vertex buffers
  38875. * @return an object holding all vertex buffers indexed by kind
  38876. */
  38877. Geometry.prototype.getVertexBuffers = function () {
  38878. if (!this.isReady()) {
  38879. return null;
  38880. }
  38881. return this._vertexBuffers;
  38882. };
  38883. /**
  38884. * Gets a boolean indicating if specific vertex buffer is present
  38885. * @param kind defines the data kind (Position, normal, etc...)
  38886. * @returns true if data is present
  38887. */
  38888. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38889. if (!this._vertexBuffers) {
  38890. if (this._delayInfo) {
  38891. return this._delayInfo.indexOf(kind) !== -1;
  38892. }
  38893. return false;
  38894. }
  38895. return this._vertexBuffers[kind] !== undefined;
  38896. };
  38897. /**
  38898. * Gets a list of all attached data kinds (Position, normal, etc...)
  38899. * @returns a list of string containing all kinds
  38900. */
  38901. Geometry.prototype.getVerticesDataKinds = function () {
  38902. var result = [];
  38903. var kind;
  38904. if (!this._vertexBuffers && this._delayInfo) {
  38905. for (kind in this._delayInfo) {
  38906. result.push(kind);
  38907. }
  38908. }
  38909. else {
  38910. for (kind in this._vertexBuffers) {
  38911. result.push(kind);
  38912. }
  38913. }
  38914. return result;
  38915. };
  38916. /**
  38917. * Update index buffer
  38918. * @param indices defines the indices to store in the index buffer
  38919. * @param offset defines the offset in the target buffer where to store the data
  38920. */
  38921. Geometry.prototype.updateIndices = function (indices, offset) {
  38922. if (!this._indexBuffer) {
  38923. return;
  38924. }
  38925. if (!this._indexBufferIsUpdatable) {
  38926. this.setIndices(indices, null, true);
  38927. }
  38928. else {
  38929. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38930. }
  38931. };
  38932. /**
  38933. * Creates a new index buffer
  38934. * @param indices defines the indices to store in the index buffer
  38935. * @param totalVertices defines the total number of vertices (could be null)
  38936. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38937. */
  38938. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38939. if (totalVertices === void 0) { totalVertices = null; }
  38940. if (updatable === void 0) { updatable = false; }
  38941. if (this._indexBuffer) {
  38942. this._engine._releaseBuffer(this._indexBuffer);
  38943. }
  38944. this._disposeVertexArrayObjects();
  38945. this._indices = indices;
  38946. this._indexBufferIsUpdatable = updatable;
  38947. if (this._meshes.length !== 0 && this._indices) {
  38948. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38949. }
  38950. if (totalVertices != undefined) { // including null and undefined
  38951. this._totalVertices = totalVertices;
  38952. }
  38953. var meshes = this._meshes;
  38954. var numOfMeshes = meshes.length;
  38955. for (var index = 0; index < numOfMeshes; index++) {
  38956. meshes[index]._createGlobalSubMesh(true);
  38957. }
  38958. this.notifyUpdate();
  38959. };
  38960. /**
  38961. * Return the total number of indices
  38962. * @returns the total number of indices
  38963. */
  38964. Geometry.prototype.getTotalIndices = function () {
  38965. if (!this.isReady()) {
  38966. return 0;
  38967. }
  38968. return this._indices.length;
  38969. };
  38970. /**
  38971. * Gets the index buffer array
  38972. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38973. * @returns the index buffer array
  38974. */
  38975. Geometry.prototype.getIndices = function (copyWhenShared) {
  38976. if (!this.isReady()) {
  38977. return null;
  38978. }
  38979. var orig = this._indices;
  38980. if (!copyWhenShared || this._meshes.length === 1) {
  38981. return orig;
  38982. }
  38983. else {
  38984. var len = orig.length;
  38985. var copy = [];
  38986. for (var i = 0; i < len; i++) {
  38987. copy.push(orig[i]);
  38988. }
  38989. return copy;
  38990. }
  38991. };
  38992. /**
  38993. * Gets the index buffer
  38994. * @return the index buffer
  38995. */
  38996. Geometry.prototype.getIndexBuffer = function () {
  38997. if (!this.isReady()) {
  38998. return null;
  38999. }
  39000. return this._indexBuffer;
  39001. };
  39002. /** @hidden */
  39003. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39004. if (effect === void 0) { effect = null; }
  39005. if (!effect || !this._vertexArrayObjects) {
  39006. return;
  39007. }
  39008. if (this._vertexArrayObjects[effect.key]) {
  39009. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39010. delete this._vertexArrayObjects[effect.key];
  39011. }
  39012. };
  39013. /**
  39014. * Release the associated resources for a specific mesh
  39015. * @param mesh defines the source mesh
  39016. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39017. */
  39018. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39019. var meshes = this._meshes;
  39020. var index = meshes.indexOf(mesh);
  39021. if (index === -1) {
  39022. return;
  39023. }
  39024. meshes.splice(index, 1);
  39025. mesh._geometry = null;
  39026. if (meshes.length === 0 && shouldDispose) {
  39027. this.dispose();
  39028. }
  39029. };
  39030. /**
  39031. * Apply current geometry to a given mesh
  39032. * @param mesh defines the mesh to apply geometry to
  39033. */
  39034. Geometry.prototype.applyToMesh = function (mesh) {
  39035. if (mesh._geometry === this) {
  39036. return;
  39037. }
  39038. var previousGeometry = mesh._geometry;
  39039. if (previousGeometry) {
  39040. previousGeometry.releaseForMesh(mesh);
  39041. }
  39042. var meshes = this._meshes;
  39043. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39044. mesh._geometry = this;
  39045. this._scene.pushGeometry(this);
  39046. meshes.push(mesh);
  39047. if (this.isReady()) {
  39048. this._applyToMesh(mesh);
  39049. }
  39050. else {
  39051. mesh._boundingInfo = this._boundingInfo;
  39052. }
  39053. };
  39054. Geometry.prototype._updateExtend = function (data) {
  39055. if (data === void 0) { data = null; }
  39056. if (!data) {
  39057. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39058. }
  39059. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39060. };
  39061. Geometry.prototype._applyToMesh = function (mesh) {
  39062. var numOfMeshes = this._meshes.length;
  39063. // vertexBuffers
  39064. for (var kind in this._vertexBuffers) {
  39065. if (numOfMeshes === 1) {
  39066. this._vertexBuffers[kind].create();
  39067. }
  39068. var buffer = this._vertexBuffers[kind].getBuffer();
  39069. if (buffer)
  39070. buffer.references = numOfMeshes;
  39071. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39072. if (!this._extend) {
  39073. this._updateExtend();
  39074. }
  39075. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39076. mesh._createGlobalSubMesh(false);
  39077. //bounding info was just created again, world matrix should be applied again.
  39078. mesh._updateBoundingInfo();
  39079. }
  39080. }
  39081. // indexBuffer
  39082. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39083. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39084. }
  39085. if (this._indexBuffer) {
  39086. this._indexBuffer.references = numOfMeshes;
  39087. }
  39088. };
  39089. Geometry.prototype.notifyUpdate = function (kind) {
  39090. if (this.onGeometryUpdated) {
  39091. this.onGeometryUpdated(this, kind);
  39092. }
  39093. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39094. var mesh = _a[_i];
  39095. mesh._markSubMeshesAsAttributesDirty();
  39096. }
  39097. };
  39098. /**
  39099. * Load the geometry if it was flagged as delay loaded
  39100. * @param scene defines the hosting scene
  39101. * @param onLoaded defines a callback called when the geometry is loaded
  39102. */
  39103. Geometry.prototype.load = function (scene, onLoaded) {
  39104. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39105. return;
  39106. }
  39107. if (this.isReady()) {
  39108. if (onLoaded) {
  39109. onLoaded();
  39110. }
  39111. return;
  39112. }
  39113. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39114. this._queueLoad(scene, onLoaded);
  39115. };
  39116. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39117. var _this = this;
  39118. if (!this.delayLoadingFile) {
  39119. return;
  39120. }
  39121. scene._addPendingData(this);
  39122. scene._loadFile(this.delayLoadingFile, function (data) {
  39123. if (!_this._delayLoadingFunction) {
  39124. return;
  39125. }
  39126. _this._delayLoadingFunction(JSON.parse(data), _this);
  39127. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39128. _this._delayInfo = [];
  39129. scene._removePendingData(_this);
  39130. var meshes = _this._meshes;
  39131. var numOfMeshes = meshes.length;
  39132. for (var index = 0; index < numOfMeshes; index++) {
  39133. _this._applyToMesh(meshes[index]);
  39134. }
  39135. if (onLoaded) {
  39136. onLoaded();
  39137. }
  39138. }, undefined, true);
  39139. };
  39140. /**
  39141. * Invert the geometry to move from a right handed system to a left handed one.
  39142. */
  39143. Geometry.prototype.toLeftHanded = function () {
  39144. // Flip faces
  39145. var tIndices = this.getIndices(false);
  39146. if (tIndices != null && tIndices.length > 0) {
  39147. for (var i = 0; i < tIndices.length; i += 3) {
  39148. var tTemp = tIndices[i + 0];
  39149. tIndices[i + 0] = tIndices[i + 2];
  39150. tIndices[i + 2] = tTemp;
  39151. }
  39152. this.setIndices(tIndices);
  39153. }
  39154. // Negate position.z
  39155. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39156. if (tPositions != null && tPositions.length > 0) {
  39157. for (var i = 0; i < tPositions.length; i += 3) {
  39158. tPositions[i + 2] = -tPositions[i + 2];
  39159. }
  39160. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39161. }
  39162. // Negate normal.z
  39163. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39164. if (tNormals != null && tNormals.length > 0) {
  39165. for (var i = 0; i < tNormals.length; i += 3) {
  39166. tNormals[i + 2] = -tNormals[i + 2];
  39167. }
  39168. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39169. }
  39170. };
  39171. // Cache
  39172. /** @hidden */
  39173. Geometry.prototype._resetPointsArrayCache = function () {
  39174. this._positions = null;
  39175. };
  39176. /** @hidden */
  39177. Geometry.prototype._generatePointsArray = function () {
  39178. if (this._positions)
  39179. return true;
  39180. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39181. if (!data || data.length === 0) {
  39182. return false;
  39183. }
  39184. this._positions = [];
  39185. for (var index = 0; index < data.length; index += 3) {
  39186. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39187. }
  39188. return true;
  39189. };
  39190. /**
  39191. * Gets a value indicating if the geometry is disposed
  39192. * @returns true if the geometry was disposed
  39193. */
  39194. Geometry.prototype.isDisposed = function () {
  39195. return this._isDisposed;
  39196. };
  39197. Geometry.prototype._disposeVertexArrayObjects = function () {
  39198. if (this._vertexArrayObjects) {
  39199. for (var kind in this._vertexArrayObjects) {
  39200. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39201. }
  39202. this._vertexArrayObjects = {};
  39203. }
  39204. };
  39205. /**
  39206. * Free all associated resources
  39207. */
  39208. Geometry.prototype.dispose = function () {
  39209. var meshes = this._meshes;
  39210. var numOfMeshes = meshes.length;
  39211. var index;
  39212. for (index = 0; index < numOfMeshes; index++) {
  39213. this.releaseForMesh(meshes[index]);
  39214. }
  39215. this._meshes = [];
  39216. this._disposeVertexArrayObjects();
  39217. for (var kind in this._vertexBuffers) {
  39218. this._vertexBuffers[kind].dispose();
  39219. }
  39220. this._vertexBuffers = {};
  39221. this._totalVertices = 0;
  39222. if (this._indexBuffer) {
  39223. this._engine._releaseBuffer(this._indexBuffer);
  39224. }
  39225. this._indexBuffer = null;
  39226. this._indices = [];
  39227. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39228. this.delayLoadingFile = null;
  39229. this._delayLoadingFunction = null;
  39230. this._delayInfo = [];
  39231. this._boundingInfo = null;
  39232. this._scene.removeGeometry(this);
  39233. this._isDisposed = true;
  39234. };
  39235. /**
  39236. * Clone the current geometry into a new geometry
  39237. * @param id defines the unique ID of the new geometry
  39238. * @returns a new geometry object
  39239. */
  39240. Geometry.prototype.copy = function (id) {
  39241. var vertexData = new BABYLON.VertexData();
  39242. vertexData.indices = [];
  39243. var indices = this.getIndices();
  39244. if (indices) {
  39245. for (var index = 0; index < indices.length; index++) {
  39246. vertexData.indices.push(indices[index]);
  39247. }
  39248. }
  39249. var updatable = false;
  39250. var stopChecking = false;
  39251. var kind;
  39252. for (kind in this._vertexBuffers) {
  39253. // using slice() to make a copy of the array and not just reference it
  39254. var data = this.getVerticesData(kind);
  39255. if (data instanceof Float32Array) {
  39256. vertexData.set(new Float32Array(data), kind);
  39257. }
  39258. else {
  39259. vertexData.set(data.slice(0), kind);
  39260. }
  39261. if (!stopChecking) {
  39262. var vb = this.getVertexBuffer(kind);
  39263. if (vb) {
  39264. updatable = vb.isUpdatable();
  39265. stopChecking = !updatable;
  39266. }
  39267. }
  39268. }
  39269. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39270. geometry.delayLoadState = this.delayLoadState;
  39271. geometry.delayLoadingFile = this.delayLoadingFile;
  39272. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39273. for (kind in this._delayInfo) {
  39274. geometry._delayInfo = geometry._delayInfo || [];
  39275. geometry._delayInfo.push(kind);
  39276. }
  39277. // Bounding info
  39278. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39279. return geometry;
  39280. };
  39281. /**
  39282. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39283. * @return a JSON representation of the current geometry data (without the vertices data)
  39284. */
  39285. Geometry.prototype.serialize = function () {
  39286. var serializationObject = {};
  39287. serializationObject.id = this.id;
  39288. serializationObject.updatable = this._updatable;
  39289. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39290. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39291. }
  39292. return serializationObject;
  39293. };
  39294. Geometry.prototype.toNumberArray = function (origin) {
  39295. if (Array.isArray(origin)) {
  39296. return origin;
  39297. }
  39298. else {
  39299. return Array.prototype.slice.call(origin);
  39300. }
  39301. };
  39302. /**
  39303. * Serialize all vertices data into a JSON oject
  39304. * @returns a JSON representation of the current geometry data
  39305. */
  39306. Geometry.prototype.serializeVerticeData = function () {
  39307. var serializationObject = this.serialize();
  39308. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39309. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39310. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39311. serializationObject.positions._updatable = true;
  39312. }
  39313. }
  39314. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39315. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39316. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39317. serializationObject.normals._updatable = true;
  39318. }
  39319. }
  39320. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39321. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39322. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39323. serializationObject.tangets._updatable = true;
  39324. }
  39325. }
  39326. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39327. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39328. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39329. serializationObject.uvs._updatable = true;
  39330. }
  39331. }
  39332. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39333. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39334. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39335. serializationObject.uv2s._updatable = true;
  39336. }
  39337. }
  39338. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39339. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39340. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39341. serializationObject.uv3s._updatable = true;
  39342. }
  39343. }
  39344. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39345. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39346. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39347. serializationObject.uv4s._updatable = true;
  39348. }
  39349. }
  39350. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39351. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39352. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39353. serializationObject.uv5s._updatable = true;
  39354. }
  39355. }
  39356. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39357. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39358. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39359. serializationObject.uv6s._updatable = true;
  39360. }
  39361. }
  39362. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39363. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39364. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39365. serializationObject.colors._updatable = true;
  39366. }
  39367. }
  39368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39369. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39370. serializationObject.matricesIndices._isExpanded = true;
  39371. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39372. serializationObject.matricesIndices._updatable = true;
  39373. }
  39374. }
  39375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39376. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39377. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39378. serializationObject.matricesWeights._updatable = true;
  39379. }
  39380. }
  39381. serializationObject.indices = this.toNumberArray(this.getIndices());
  39382. return serializationObject;
  39383. };
  39384. // Statics
  39385. /**
  39386. * Extracts a clone of a mesh geometry
  39387. * @param mesh defines the source mesh
  39388. * @param id defines the unique ID of the new geometry object
  39389. * @returns the new geometry object
  39390. */
  39391. Geometry.ExtractFromMesh = function (mesh, id) {
  39392. var geometry = mesh._geometry;
  39393. if (!geometry) {
  39394. return null;
  39395. }
  39396. return geometry.copy(id);
  39397. };
  39398. /**
  39399. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39400. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39401. * Be aware Math.random() could cause collisions, but:
  39402. * "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"
  39403. * @returns a string containing a new GUID
  39404. */
  39405. Geometry.RandomId = function () {
  39406. return BABYLON.Tools.RandomId();
  39407. };
  39408. /** @hidden */
  39409. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39410. var scene = mesh.getScene();
  39411. // Geometry
  39412. var geometryId = parsedGeometry.geometryId;
  39413. if (geometryId) {
  39414. var geometry = scene.getGeometryByID(geometryId);
  39415. if (geometry) {
  39416. geometry.applyToMesh(mesh);
  39417. }
  39418. }
  39419. else if (parsedGeometry instanceof ArrayBuffer) {
  39420. var binaryInfo = mesh._binaryInfo;
  39421. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39422. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39423. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39424. }
  39425. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39426. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39427. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39428. }
  39429. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39430. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39431. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39432. }
  39433. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39434. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39435. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39436. }
  39437. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39438. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39439. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39440. }
  39441. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39442. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39443. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39444. }
  39445. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39446. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39447. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39448. }
  39449. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39450. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39451. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39452. }
  39453. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39454. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39455. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39456. }
  39457. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39458. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39459. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39460. }
  39461. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39462. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39463. var floatIndices = [];
  39464. for (var i = 0; i < matricesIndicesData.length; i++) {
  39465. var index = matricesIndicesData[i];
  39466. floatIndices.push(index & 0x000000FF);
  39467. floatIndices.push((index & 0x0000FF00) >> 8);
  39468. floatIndices.push((index & 0x00FF0000) >> 16);
  39469. floatIndices.push(index >> 24);
  39470. }
  39471. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39472. }
  39473. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39474. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39476. }
  39477. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39478. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39479. mesh.setIndices(indicesData, null);
  39480. }
  39481. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39482. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39483. mesh.subMeshes = [];
  39484. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39485. var materialIndex = subMeshesData[(i * 5) + 0];
  39486. var verticesStart = subMeshesData[(i * 5) + 1];
  39487. var verticesCount = subMeshesData[(i * 5) + 2];
  39488. var indexStart = subMeshesData[(i * 5) + 3];
  39489. var indexCount = subMeshesData[(i * 5) + 4];
  39490. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39491. }
  39492. }
  39493. }
  39494. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39496. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39497. if (parsedGeometry.tangents) {
  39498. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39499. }
  39500. if (parsedGeometry.uvs) {
  39501. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39502. }
  39503. if (parsedGeometry.uvs2) {
  39504. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39505. }
  39506. if (parsedGeometry.uvs3) {
  39507. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39508. }
  39509. if (parsedGeometry.uvs4) {
  39510. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39511. }
  39512. if (parsedGeometry.uvs5) {
  39513. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39514. }
  39515. if (parsedGeometry.uvs6) {
  39516. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39517. }
  39518. if (parsedGeometry.colors) {
  39519. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39520. }
  39521. if (parsedGeometry.matricesIndices) {
  39522. if (!parsedGeometry.matricesIndices._isExpanded) {
  39523. var floatIndices = [];
  39524. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39525. var matricesIndex = parsedGeometry.matricesIndices[i];
  39526. floatIndices.push(matricesIndex & 0x000000FF);
  39527. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39528. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39529. floatIndices.push(matricesIndex >> 24);
  39530. }
  39531. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39532. }
  39533. else {
  39534. delete parsedGeometry.matricesIndices._isExpanded;
  39535. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39536. }
  39537. }
  39538. if (parsedGeometry.matricesIndicesExtra) {
  39539. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39540. var floatIndices = [];
  39541. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39542. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39543. floatIndices.push(matricesIndex & 0x000000FF);
  39544. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39545. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39546. floatIndices.push(matricesIndex >> 24);
  39547. }
  39548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39549. }
  39550. else {
  39551. delete parsedGeometry.matricesIndices._isExpanded;
  39552. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39553. }
  39554. }
  39555. if (parsedGeometry.matricesWeights) {
  39556. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39557. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39558. }
  39559. if (parsedGeometry.matricesWeightsExtra) {
  39560. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39561. }
  39562. mesh.setIndices(parsedGeometry.indices, null);
  39563. }
  39564. // SubMeshes
  39565. if (parsedGeometry.subMeshes) {
  39566. mesh.subMeshes = [];
  39567. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39568. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39569. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39570. }
  39571. }
  39572. // Flat shading
  39573. if (mesh._shouldGenerateFlatShading) {
  39574. mesh.convertToFlatShadedMesh();
  39575. delete mesh._shouldGenerateFlatShading;
  39576. }
  39577. // Update
  39578. mesh.computeWorldMatrix(true);
  39579. // Octree
  39580. var sceneOctree = scene.selectionOctree;
  39581. if (sceneOctree !== undefined && sceneOctree !== null) {
  39582. sceneOctree.addMesh(mesh);
  39583. }
  39584. };
  39585. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39586. var epsilon = 1e-3;
  39587. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39588. return;
  39589. }
  39590. var noInfluenceBoneIndex = 0.0;
  39591. if (parsedGeometry.skeletonId > -1) {
  39592. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39593. if (!skeleton) {
  39594. return;
  39595. }
  39596. noInfluenceBoneIndex = skeleton.bones.length;
  39597. }
  39598. else {
  39599. return;
  39600. }
  39601. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39602. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39603. var matricesWeights = parsedGeometry.matricesWeights;
  39604. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39605. var influencers = parsedGeometry.numBoneInfluencer;
  39606. var size = matricesWeights.length;
  39607. for (var i = 0; i < size; i += 4) {
  39608. var weight = 0.0;
  39609. var firstZeroWeight = -1;
  39610. for (var j = 0; j < 4; j++) {
  39611. var w = matricesWeights[i + j];
  39612. weight += w;
  39613. if (w < epsilon && firstZeroWeight < 0) {
  39614. firstZeroWeight = j;
  39615. }
  39616. }
  39617. if (matricesWeightsExtra) {
  39618. for (var j = 0; j < 4; j++) {
  39619. var w = matricesWeightsExtra[i + j];
  39620. weight += w;
  39621. if (w < epsilon && firstZeroWeight < 0) {
  39622. firstZeroWeight = j + 4;
  39623. }
  39624. }
  39625. }
  39626. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39627. firstZeroWeight = influencers - 1;
  39628. }
  39629. if (weight > epsilon) {
  39630. var mweight = 1.0 / weight;
  39631. for (var j = 0; j < 4; j++) {
  39632. matricesWeights[i + j] *= mweight;
  39633. }
  39634. if (matricesWeightsExtra) {
  39635. for (var j = 0; j < 4; j++) {
  39636. matricesWeightsExtra[i + j] *= mweight;
  39637. }
  39638. }
  39639. }
  39640. else {
  39641. if (firstZeroWeight >= 4) {
  39642. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39643. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39644. }
  39645. else {
  39646. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39647. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39648. }
  39649. }
  39650. }
  39651. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39652. if (parsedGeometry.matricesWeightsExtra) {
  39653. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39654. }
  39655. };
  39656. /**
  39657. * Create a new geometry from persisted data (Using .babylon file format)
  39658. * @param parsedVertexData defines the persisted data
  39659. * @param scene defines the hosting scene
  39660. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39661. * @returns the new geometry object
  39662. */
  39663. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39664. if (scene.getGeometryByID(parsedVertexData.id)) {
  39665. return null; // null since geometry could be something else than a box...
  39666. }
  39667. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39668. if (BABYLON.Tags) {
  39669. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39670. }
  39671. if (parsedVertexData.delayLoadingFile) {
  39672. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39673. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39674. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39675. geometry._delayInfo = [];
  39676. if (parsedVertexData.hasUVs) {
  39677. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39678. }
  39679. if (parsedVertexData.hasUVs2) {
  39680. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39681. }
  39682. if (parsedVertexData.hasUVs3) {
  39683. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39684. }
  39685. if (parsedVertexData.hasUVs4) {
  39686. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39687. }
  39688. if (parsedVertexData.hasUVs5) {
  39689. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39690. }
  39691. if (parsedVertexData.hasUVs6) {
  39692. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39693. }
  39694. if (parsedVertexData.hasColors) {
  39695. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39696. }
  39697. if (parsedVertexData.hasMatricesIndices) {
  39698. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39699. }
  39700. if (parsedVertexData.hasMatricesWeights) {
  39701. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39702. }
  39703. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39704. }
  39705. else {
  39706. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39707. }
  39708. scene.pushGeometry(geometry, true);
  39709. return geometry;
  39710. };
  39711. return Geometry;
  39712. }());
  39713. BABYLON.Geometry = Geometry;
  39714. // Primitives
  39715. /// Abstract class
  39716. /**
  39717. * Abstract class used to provide common services for all typed geometries
  39718. * @hidden
  39719. */
  39720. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39721. __extends(_PrimitiveGeometry, _super);
  39722. /**
  39723. * Creates a new typed geometry
  39724. * @param id defines the unique ID of the geometry
  39725. * @param scene defines the hosting scene
  39726. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39727. * @param mesh defines the hosting mesh (can be null)
  39728. */
  39729. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39730. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39731. if (mesh === void 0) { mesh = null; }
  39732. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39733. _this._canBeRegenerated = _canBeRegenerated;
  39734. _this._beingRegenerated = true;
  39735. _this.regenerate();
  39736. _this._beingRegenerated = false;
  39737. return _this;
  39738. }
  39739. /**
  39740. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39741. * @returns true if the geometry can be regenerated
  39742. */
  39743. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39744. return this._canBeRegenerated;
  39745. };
  39746. /**
  39747. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39748. */
  39749. _PrimitiveGeometry.prototype.regenerate = function () {
  39750. if (!this._canBeRegenerated) {
  39751. return;
  39752. }
  39753. this._beingRegenerated = true;
  39754. this.setAllVerticesData(this._regenerateVertexData(), false);
  39755. this._beingRegenerated = false;
  39756. };
  39757. /**
  39758. * Clone the geometry
  39759. * @param id defines the unique ID of the new geometry
  39760. * @returns the new geometry
  39761. */
  39762. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39763. return _super.prototype.copy.call(this, id);
  39764. };
  39765. // overrides
  39766. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39767. if (!this._beingRegenerated) {
  39768. return;
  39769. }
  39770. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39771. };
  39772. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39773. if (!this._beingRegenerated) {
  39774. return;
  39775. }
  39776. _super.prototype.setVerticesData.call(this, kind, data, false);
  39777. };
  39778. // to override
  39779. /** @hidden */
  39780. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39781. throw new Error("Abstract method");
  39782. };
  39783. _PrimitiveGeometry.prototype.copy = function (id) {
  39784. throw new Error("Must be overriden in sub-classes.");
  39785. };
  39786. _PrimitiveGeometry.prototype.serialize = function () {
  39787. var serializationObject = _super.prototype.serialize.call(this);
  39788. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39789. return serializationObject;
  39790. };
  39791. return _PrimitiveGeometry;
  39792. }(Geometry));
  39793. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39794. /**
  39795. * Creates a ribbon geometry
  39796. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39797. */
  39798. var RibbonGeometry = /** @class */ (function (_super) {
  39799. __extends(RibbonGeometry, _super);
  39800. /**
  39801. * Creates a ribbon geometry
  39802. * @param id defines the unique ID of the geometry
  39803. * @param scene defines the hosting scene
  39804. * @param pathArray defines the array of paths to use
  39805. * @param closeArray defines if the last path and the first path must be joined
  39806. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39807. * @param offset defines the offset between points
  39808. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39809. * @param mesh defines the hosting mesh (can be null)
  39810. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39811. */
  39812. function RibbonGeometry(id, scene,
  39813. /**
  39814. * Defines the array of paths to use
  39815. */
  39816. pathArray,
  39817. /**
  39818. * Defines if the last and first points of each path in your pathArray must be joined
  39819. */
  39820. closeArray,
  39821. /**
  39822. * Defines if the last and first points of each path in your pathArray must be joined
  39823. */
  39824. closePath,
  39825. /**
  39826. * Defines the offset between points
  39827. */
  39828. offset, canBeRegenerated, mesh,
  39829. /**
  39830. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39831. */
  39832. side) {
  39833. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39834. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39835. _this.pathArray = pathArray;
  39836. _this.closeArray = closeArray;
  39837. _this.closePath = closePath;
  39838. _this.offset = offset;
  39839. _this.side = side;
  39840. return _this;
  39841. }
  39842. /** @hidden */
  39843. RibbonGeometry.prototype._regenerateVertexData = function () {
  39844. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39845. };
  39846. RibbonGeometry.prototype.copy = function (id) {
  39847. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39848. };
  39849. return RibbonGeometry;
  39850. }(_PrimitiveGeometry));
  39851. BABYLON.RibbonGeometry = RibbonGeometry;
  39852. /**
  39853. * Creates a box geometry
  39854. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39855. */
  39856. var BoxGeometry = /** @class */ (function (_super) {
  39857. __extends(BoxGeometry, _super);
  39858. /**
  39859. * Creates a box geometry
  39860. * @param id defines the unique ID of the geometry
  39861. * @param scene defines the hosting scene
  39862. * @param size defines the zise of the box (width, height and depth are the same)
  39863. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39864. * @param mesh defines the hosting mesh (can be null)
  39865. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39866. */
  39867. function BoxGeometry(id, scene,
  39868. /**
  39869. * Defines the zise of the box (width, height and depth are the same)
  39870. */
  39871. size, canBeRegenerated, mesh,
  39872. /**
  39873. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39874. */
  39875. side) {
  39876. if (mesh === void 0) { mesh = null; }
  39877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39878. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39879. _this.size = size;
  39880. _this.side = side;
  39881. return _this;
  39882. }
  39883. BoxGeometry.prototype._regenerateVertexData = function () {
  39884. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39885. };
  39886. BoxGeometry.prototype.copy = function (id) {
  39887. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39888. };
  39889. BoxGeometry.prototype.serialize = function () {
  39890. var serializationObject = _super.prototype.serialize.call(this);
  39891. serializationObject.size = this.size;
  39892. return serializationObject;
  39893. };
  39894. BoxGeometry.Parse = function (parsedBox, scene) {
  39895. if (scene.getGeometryByID(parsedBox.id)) {
  39896. return null; // null since geometry could be something else than a box...
  39897. }
  39898. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39899. if (BABYLON.Tags) {
  39900. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39901. }
  39902. scene.pushGeometry(box, true);
  39903. return box;
  39904. };
  39905. return BoxGeometry;
  39906. }(_PrimitiveGeometry));
  39907. BABYLON.BoxGeometry = BoxGeometry;
  39908. /**
  39909. * Creates a sphere geometry
  39910. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39911. */
  39912. var SphereGeometry = /** @class */ (function (_super) {
  39913. __extends(SphereGeometry, _super);
  39914. /**
  39915. * Create a new sphere geometry
  39916. * @param id defines the unique ID of the geometry
  39917. * @param scene defines the hosting scene
  39918. * @param segments defines the number of segments to use to create the sphere
  39919. * @param diameter defines the diameter of the sphere
  39920. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39921. * @param mesh defines the hosting mesh (can be null)
  39922. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39923. */
  39924. function SphereGeometry(id, scene,
  39925. /**
  39926. * Defines the number of segments to use to create the sphere
  39927. */
  39928. segments,
  39929. /**
  39930. * Defines the diameter of the sphere
  39931. */
  39932. diameter, canBeRegenerated, mesh,
  39933. /**
  39934. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39935. */
  39936. side) {
  39937. if (mesh === void 0) { mesh = null; }
  39938. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39939. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39940. _this.segments = segments;
  39941. _this.diameter = diameter;
  39942. _this.side = side;
  39943. return _this;
  39944. }
  39945. SphereGeometry.prototype._regenerateVertexData = function () {
  39946. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39947. };
  39948. SphereGeometry.prototype.copy = function (id) {
  39949. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39950. };
  39951. SphereGeometry.prototype.serialize = function () {
  39952. var serializationObject = _super.prototype.serialize.call(this);
  39953. serializationObject.segments = this.segments;
  39954. serializationObject.diameter = this.diameter;
  39955. return serializationObject;
  39956. };
  39957. SphereGeometry.Parse = function (parsedSphere, scene) {
  39958. if (scene.getGeometryByID(parsedSphere.id)) {
  39959. return null; // null since geometry could be something else than a sphere...
  39960. }
  39961. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39962. if (BABYLON.Tags) {
  39963. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39964. }
  39965. scene.pushGeometry(sphere, true);
  39966. return sphere;
  39967. };
  39968. return SphereGeometry;
  39969. }(_PrimitiveGeometry));
  39970. BABYLON.SphereGeometry = SphereGeometry;
  39971. /**
  39972. * Creates a disc geometry
  39973. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39974. */
  39975. var DiscGeometry = /** @class */ (function (_super) {
  39976. __extends(DiscGeometry, _super);
  39977. /**
  39978. * Creates a new disc geometry
  39979. * @param id defines the unique ID of the geometry
  39980. * @param scene defines the hosting scene
  39981. * @param radius defines the radius of the disc
  39982. * @param tessellation defines the tesselation factor to apply to the disc
  39983. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39984. * @param mesh defines the hosting mesh (can be null)
  39985. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39986. */
  39987. function DiscGeometry(id, scene,
  39988. /**
  39989. * Defines the radius of the disc
  39990. */
  39991. radius,
  39992. /**
  39993. * Defines the tesselation factor to apply to the disc
  39994. */
  39995. tessellation, canBeRegenerated, mesh,
  39996. /**
  39997. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39998. */
  39999. side) {
  40000. if (mesh === void 0) { mesh = null; }
  40001. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40002. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40003. _this.radius = radius;
  40004. _this.tessellation = tessellation;
  40005. _this.side = side;
  40006. return _this;
  40007. }
  40008. DiscGeometry.prototype._regenerateVertexData = function () {
  40009. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40010. };
  40011. DiscGeometry.prototype.copy = function (id) {
  40012. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40013. };
  40014. return DiscGeometry;
  40015. }(_PrimitiveGeometry));
  40016. BABYLON.DiscGeometry = DiscGeometry;
  40017. /**
  40018. * Creates a new cylinder geometry
  40019. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40020. */
  40021. var CylinderGeometry = /** @class */ (function (_super) {
  40022. __extends(CylinderGeometry, _super);
  40023. /**
  40024. * Creates a new cylinder geometry
  40025. * @param id defines the unique ID of the geometry
  40026. * @param scene defines the hosting scene
  40027. * @param height defines the height of the cylinder
  40028. * @param diameterTop defines the diameter of the cylinder's top cap
  40029. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40030. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40031. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40032. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40033. * @param mesh defines the hosting mesh (can be null)
  40034. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40035. */
  40036. function CylinderGeometry(id, scene,
  40037. /**
  40038. * Defines the height of the cylinder
  40039. */
  40040. height,
  40041. /**
  40042. * Defines the diameter of the cylinder's top cap
  40043. */
  40044. diameterTop,
  40045. /**
  40046. * Defines the diameter of the cylinder's bottom cap
  40047. */
  40048. diameterBottom,
  40049. /**
  40050. * Defines the tessellation factor to apply to the cylinder
  40051. */
  40052. tessellation,
  40053. /**
  40054. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40055. */
  40056. subdivisions, canBeRegenerated, mesh,
  40057. /**
  40058. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40059. */
  40060. side) {
  40061. if (subdivisions === void 0) { subdivisions = 1; }
  40062. if (mesh === void 0) { mesh = null; }
  40063. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40064. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40065. _this.height = height;
  40066. _this.diameterTop = diameterTop;
  40067. _this.diameterBottom = diameterBottom;
  40068. _this.tessellation = tessellation;
  40069. _this.subdivisions = subdivisions;
  40070. _this.side = side;
  40071. return _this;
  40072. }
  40073. CylinderGeometry.prototype._regenerateVertexData = function () {
  40074. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40075. };
  40076. CylinderGeometry.prototype.copy = function (id) {
  40077. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40078. };
  40079. CylinderGeometry.prototype.serialize = function () {
  40080. var serializationObject = _super.prototype.serialize.call(this);
  40081. serializationObject.height = this.height;
  40082. serializationObject.diameterTop = this.diameterTop;
  40083. serializationObject.diameterBottom = this.diameterBottom;
  40084. serializationObject.tessellation = this.tessellation;
  40085. return serializationObject;
  40086. };
  40087. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40088. if (scene.getGeometryByID(parsedCylinder.id)) {
  40089. return null; // null since geometry could be something else than a cylinder...
  40090. }
  40091. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40092. if (BABYLON.Tags) {
  40093. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40094. }
  40095. scene.pushGeometry(cylinder, true);
  40096. return cylinder;
  40097. };
  40098. return CylinderGeometry;
  40099. }(_PrimitiveGeometry));
  40100. BABYLON.CylinderGeometry = CylinderGeometry;
  40101. /**
  40102. * Creates a new torus geometry
  40103. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40104. */
  40105. var TorusGeometry = /** @class */ (function (_super) {
  40106. __extends(TorusGeometry, _super);
  40107. /**
  40108. * Creates a new torus geometry
  40109. * @param id defines the unique ID of the geometry
  40110. * @param scene defines the hosting scene
  40111. * @param diameter defines the diameter of the torus
  40112. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40113. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40114. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40115. * @param mesh defines the hosting mesh (can be null)
  40116. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40117. */
  40118. function TorusGeometry(id, scene,
  40119. /**
  40120. * Defines the diameter of the torus
  40121. */
  40122. diameter,
  40123. /**
  40124. * Defines the thickness of the torus (ie. internal diameter)
  40125. */
  40126. thickness,
  40127. /**
  40128. * Defines the tesselation factor to apply to the torus
  40129. */
  40130. tessellation, canBeRegenerated, mesh,
  40131. /**
  40132. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40133. */
  40134. side) {
  40135. if (mesh === void 0) { mesh = null; }
  40136. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40137. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40138. _this.diameter = diameter;
  40139. _this.thickness = thickness;
  40140. _this.tessellation = tessellation;
  40141. _this.side = side;
  40142. return _this;
  40143. }
  40144. TorusGeometry.prototype._regenerateVertexData = function () {
  40145. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40146. };
  40147. TorusGeometry.prototype.copy = function (id) {
  40148. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40149. };
  40150. TorusGeometry.prototype.serialize = function () {
  40151. var serializationObject = _super.prototype.serialize.call(this);
  40152. serializationObject.diameter = this.diameter;
  40153. serializationObject.thickness = this.thickness;
  40154. serializationObject.tessellation = this.tessellation;
  40155. return serializationObject;
  40156. };
  40157. TorusGeometry.Parse = function (parsedTorus, scene) {
  40158. if (scene.getGeometryByID(parsedTorus.id)) {
  40159. return null; // null since geometry could be something else than a torus...
  40160. }
  40161. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40162. if (BABYLON.Tags) {
  40163. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40164. }
  40165. scene.pushGeometry(torus, true);
  40166. return torus;
  40167. };
  40168. return TorusGeometry;
  40169. }(_PrimitiveGeometry));
  40170. BABYLON.TorusGeometry = TorusGeometry;
  40171. /**
  40172. * Creates a new ground geometry
  40173. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40174. */
  40175. var GroundGeometry = /** @class */ (function (_super) {
  40176. __extends(GroundGeometry, _super);
  40177. /**
  40178. * Creates a new ground geometry
  40179. * @param id defines the unique ID of the geometry
  40180. * @param scene defines the hosting scene
  40181. * @param width defines the width of the ground
  40182. * @param height defines the height of the ground
  40183. * @param subdivisions defines the subdivisions to apply to the ground
  40184. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40185. * @param mesh defines the hosting mesh (can be null)
  40186. */
  40187. function GroundGeometry(id, scene,
  40188. /**
  40189. * Defines the width of the ground
  40190. */
  40191. width,
  40192. /**
  40193. * Defines the height of the ground
  40194. */
  40195. height,
  40196. /**
  40197. * Defines the subdivisions to apply to the ground
  40198. */
  40199. subdivisions, canBeRegenerated, mesh) {
  40200. if (mesh === void 0) { mesh = null; }
  40201. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40202. _this.width = width;
  40203. _this.height = height;
  40204. _this.subdivisions = subdivisions;
  40205. return _this;
  40206. }
  40207. GroundGeometry.prototype._regenerateVertexData = function () {
  40208. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40209. };
  40210. GroundGeometry.prototype.copy = function (id) {
  40211. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40212. };
  40213. GroundGeometry.prototype.serialize = function () {
  40214. var serializationObject = _super.prototype.serialize.call(this);
  40215. serializationObject.width = this.width;
  40216. serializationObject.height = this.height;
  40217. serializationObject.subdivisions = this.subdivisions;
  40218. return serializationObject;
  40219. };
  40220. GroundGeometry.Parse = function (parsedGround, scene) {
  40221. if (scene.getGeometryByID(parsedGround.id)) {
  40222. return null; // null since geometry could be something else than a ground...
  40223. }
  40224. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40225. if (BABYLON.Tags) {
  40226. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40227. }
  40228. scene.pushGeometry(ground, true);
  40229. return ground;
  40230. };
  40231. return GroundGeometry;
  40232. }(_PrimitiveGeometry));
  40233. BABYLON.GroundGeometry = GroundGeometry;
  40234. /**
  40235. * Creates a tiled ground geometry
  40236. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40237. */
  40238. var TiledGroundGeometry = /** @class */ (function (_super) {
  40239. __extends(TiledGroundGeometry, _super);
  40240. /**
  40241. * Creates a tiled ground geometry
  40242. * @param id defines the unique ID of the geometry
  40243. * @param scene defines the hosting scene
  40244. * @param xmin defines the minimum value on X axis
  40245. * @param zmin defines the minimum value on Z axis
  40246. * @param xmax defines the maximum value on X axis
  40247. * @param zmax defines the maximum value on Z axis
  40248. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40249. * @param precision defines the precision to use when computing the tiles
  40250. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40251. * @param mesh defines the hosting mesh (can be null)
  40252. */
  40253. function TiledGroundGeometry(id, scene,
  40254. /**
  40255. * Defines the minimum value on X axis
  40256. */
  40257. xmin,
  40258. /**
  40259. * Defines the minimum value on Z axis
  40260. */
  40261. zmin,
  40262. /**
  40263. * Defines the maximum value on X axis
  40264. */
  40265. xmax,
  40266. /**
  40267. * Defines the maximum value on Z axis
  40268. */
  40269. zmax,
  40270. /**
  40271. * Defines the subdivisions to apply to the ground
  40272. */
  40273. subdivisions,
  40274. /**
  40275. * Defines the precision to use when computing the tiles
  40276. */
  40277. precision, canBeRegenerated, mesh) {
  40278. if (mesh === void 0) { mesh = null; }
  40279. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40280. _this.xmin = xmin;
  40281. _this.zmin = zmin;
  40282. _this.xmax = xmax;
  40283. _this.zmax = zmax;
  40284. _this.subdivisions = subdivisions;
  40285. _this.precision = precision;
  40286. return _this;
  40287. }
  40288. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40289. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40290. };
  40291. TiledGroundGeometry.prototype.copy = function (id) {
  40292. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40293. };
  40294. return TiledGroundGeometry;
  40295. }(_PrimitiveGeometry));
  40296. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40297. /**
  40298. * Creates a plane geometry
  40299. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40300. */
  40301. var PlaneGeometry = /** @class */ (function (_super) {
  40302. __extends(PlaneGeometry, _super);
  40303. /**
  40304. * Creates a plane geometry
  40305. * @param id defines the unique ID of the geometry
  40306. * @param scene defines the hosting scene
  40307. * @param size defines the size of the plane (width === height)
  40308. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40309. * @param mesh defines the hosting mesh (can be null)
  40310. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40311. */
  40312. function PlaneGeometry(id, scene,
  40313. /**
  40314. * Defines the size of the plane (width === height)
  40315. */
  40316. size, canBeRegenerated, mesh,
  40317. /**
  40318. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40319. */
  40320. side) {
  40321. if (mesh === void 0) { mesh = null; }
  40322. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40323. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40324. _this.size = size;
  40325. _this.side = side;
  40326. return _this;
  40327. }
  40328. PlaneGeometry.prototype._regenerateVertexData = function () {
  40329. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40330. };
  40331. PlaneGeometry.prototype.copy = function (id) {
  40332. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40333. };
  40334. PlaneGeometry.prototype.serialize = function () {
  40335. var serializationObject = _super.prototype.serialize.call(this);
  40336. serializationObject.size = this.size;
  40337. return serializationObject;
  40338. };
  40339. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40340. if (scene.getGeometryByID(parsedPlane.id)) {
  40341. return null; // null since geometry could be something else than a ground...
  40342. }
  40343. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40344. if (BABYLON.Tags) {
  40345. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40346. }
  40347. scene.pushGeometry(plane, true);
  40348. return plane;
  40349. };
  40350. return PlaneGeometry;
  40351. }(_PrimitiveGeometry));
  40352. BABYLON.PlaneGeometry = PlaneGeometry;
  40353. /**
  40354. * Creates a torus knot geometry
  40355. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40356. */
  40357. var TorusKnotGeometry = /** @class */ (function (_super) {
  40358. __extends(TorusKnotGeometry, _super);
  40359. /**
  40360. * Creates a torus knot geometry
  40361. * @param id defines the unique ID of the geometry
  40362. * @param scene defines the hosting scene
  40363. * @param radius defines the radius of the torus knot
  40364. * @param tube defines the thickness of the torus knot tube
  40365. * @param radialSegments defines the number of radial segments
  40366. * @param tubularSegments defines the number of tubular segments
  40367. * @param p defines the first number of windings
  40368. * @param q defines the second number of windings
  40369. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40370. * @param mesh defines the hosting mesh (can be null)
  40371. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40372. */
  40373. function TorusKnotGeometry(id, scene,
  40374. /**
  40375. * Defines the radius of the torus knot
  40376. */
  40377. radius,
  40378. /**
  40379. * Defines the thickness of the torus knot tube
  40380. */
  40381. tube,
  40382. /**
  40383. * Defines the number of radial segments
  40384. */
  40385. radialSegments,
  40386. /**
  40387. * Defines the number of tubular segments
  40388. */
  40389. tubularSegments,
  40390. /**
  40391. * Defines the first number of windings
  40392. */
  40393. p,
  40394. /**
  40395. * Defines the second number of windings
  40396. */
  40397. q, canBeRegenerated, mesh,
  40398. /**
  40399. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40400. */
  40401. side) {
  40402. if (mesh === void 0) { mesh = null; }
  40403. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40404. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40405. _this.radius = radius;
  40406. _this.tube = tube;
  40407. _this.radialSegments = radialSegments;
  40408. _this.tubularSegments = tubularSegments;
  40409. _this.p = p;
  40410. _this.q = q;
  40411. _this.side = side;
  40412. return _this;
  40413. }
  40414. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40415. 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 });
  40416. };
  40417. TorusKnotGeometry.prototype.copy = function (id) {
  40418. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40419. };
  40420. TorusKnotGeometry.prototype.serialize = function () {
  40421. var serializationObject = _super.prototype.serialize.call(this);
  40422. serializationObject.radius = this.radius;
  40423. serializationObject.tube = this.tube;
  40424. serializationObject.radialSegments = this.radialSegments;
  40425. serializationObject.tubularSegments = this.tubularSegments;
  40426. serializationObject.p = this.p;
  40427. serializationObject.q = this.q;
  40428. return serializationObject;
  40429. };
  40430. ;
  40431. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40432. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40433. return null; // null since geometry could be something else than a ground...
  40434. }
  40435. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40436. if (BABYLON.Tags) {
  40437. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40438. }
  40439. scene.pushGeometry(torusKnot, true);
  40440. return torusKnot;
  40441. };
  40442. return TorusKnotGeometry;
  40443. }(_PrimitiveGeometry));
  40444. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40445. //}
  40446. })(BABYLON || (BABYLON = {}));
  40447. //# sourceMappingURL=babylon.geometry.js.map
  40448. var BABYLON;
  40449. (function (BABYLON) {
  40450. /**
  40451. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40452. */
  40453. var PerformanceMonitor = /** @class */ (function () {
  40454. /**
  40455. * constructor
  40456. * @param frameSampleSize The number of samples required to saturate the sliding window
  40457. */
  40458. function PerformanceMonitor(frameSampleSize) {
  40459. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40460. this._enabled = true;
  40461. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40462. }
  40463. /**
  40464. * Samples current frame
  40465. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40466. */
  40467. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40468. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40469. if (!this._enabled)
  40470. return;
  40471. if (this._lastFrameTimeMs != null) {
  40472. var dt = timeMs - this._lastFrameTimeMs;
  40473. this._rollingFrameTime.add(dt);
  40474. }
  40475. this._lastFrameTimeMs = timeMs;
  40476. };
  40477. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40478. /**
  40479. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40480. * @return Average frame time in milliseconds
  40481. */
  40482. get: function () {
  40483. return this._rollingFrameTime.average;
  40484. },
  40485. enumerable: true,
  40486. configurable: true
  40487. });
  40488. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40489. /**
  40490. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40491. * @return Frame time variance in milliseconds squared
  40492. */
  40493. get: function () {
  40494. return this._rollingFrameTime.variance;
  40495. },
  40496. enumerable: true,
  40497. configurable: true
  40498. });
  40499. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40500. /**
  40501. * Returns the frame time of the most recent frame
  40502. * @return Frame time in milliseconds
  40503. */
  40504. get: function () {
  40505. return this._rollingFrameTime.history(0);
  40506. },
  40507. enumerable: true,
  40508. configurable: true
  40509. });
  40510. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40511. /**
  40512. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40513. * @return Framerate in frames per second
  40514. */
  40515. get: function () {
  40516. return 1000.0 / this._rollingFrameTime.average;
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40522. /**
  40523. * Returns the average framerate in frames per second using the most recent frame time
  40524. * @return Framerate in frames per second
  40525. */
  40526. get: function () {
  40527. var history = this._rollingFrameTime.history(0);
  40528. if (history === 0) {
  40529. return 0;
  40530. }
  40531. return 1000.0 / history;
  40532. },
  40533. enumerable: true,
  40534. configurable: true
  40535. });
  40536. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40537. /**
  40538. * Returns true if enough samples have been taken to completely fill the sliding window
  40539. * @return true if saturated
  40540. */
  40541. get: function () {
  40542. return this._rollingFrameTime.isSaturated();
  40543. },
  40544. enumerable: true,
  40545. configurable: true
  40546. });
  40547. /**
  40548. * Enables contributions to the sliding window sample set
  40549. */
  40550. PerformanceMonitor.prototype.enable = function () {
  40551. this._enabled = true;
  40552. };
  40553. /**
  40554. * Disables contributions to the sliding window sample set
  40555. * Samples will not be interpolated over the disabled period
  40556. */
  40557. PerformanceMonitor.prototype.disable = function () {
  40558. this._enabled = false;
  40559. //clear last sample to avoid interpolating over the disabled period when next enabled
  40560. this._lastFrameTimeMs = null;
  40561. };
  40562. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40563. /**
  40564. * Returns true if sampling is enabled
  40565. * @return true if enabled
  40566. */
  40567. get: function () {
  40568. return this._enabled;
  40569. },
  40570. enumerable: true,
  40571. configurable: true
  40572. });
  40573. /**
  40574. * Resets performance monitor
  40575. */
  40576. PerformanceMonitor.prototype.reset = function () {
  40577. //clear last sample to avoid interpolating over the disabled period when next enabled
  40578. this._lastFrameTimeMs = null;
  40579. //wipe record
  40580. this._rollingFrameTime.reset();
  40581. };
  40582. return PerformanceMonitor;
  40583. }());
  40584. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40585. /**
  40586. * RollingAverage
  40587. *
  40588. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40589. */
  40590. var RollingAverage = /** @class */ (function () {
  40591. /**
  40592. * constructor
  40593. * @param length The number of samples required to saturate the sliding window
  40594. */
  40595. function RollingAverage(length) {
  40596. this._samples = new Array(length);
  40597. this.reset();
  40598. }
  40599. /**
  40600. * Adds a sample to the sample set
  40601. * @param v The sample value
  40602. */
  40603. RollingAverage.prototype.add = function (v) {
  40604. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40605. var delta;
  40606. //we need to check if we've already wrapped round
  40607. if (this.isSaturated()) {
  40608. //remove bottom of stack from mean
  40609. var bottomValue = this._samples[this._pos];
  40610. delta = bottomValue - this.average;
  40611. this.average -= delta / (this._sampleCount - 1);
  40612. this._m2 -= delta * (bottomValue - this.average);
  40613. }
  40614. else {
  40615. this._sampleCount++;
  40616. }
  40617. //add new value to mean
  40618. delta = v - this.average;
  40619. this.average += delta / (this._sampleCount);
  40620. this._m2 += delta * (v - this.average);
  40621. //set the new variance
  40622. this.variance = this._m2 / (this._sampleCount - 1);
  40623. this._samples[this._pos] = v;
  40624. this._pos++;
  40625. this._pos %= this._samples.length; //positive wrap around
  40626. };
  40627. /**
  40628. * Returns previously added values or null if outside of history or outside the sliding window domain
  40629. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40630. * @return Value previously recorded with add() or null if outside of range
  40631. */
  40632. RollingAverage.prototype.history = function (i) {
  40633. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40634. return 0;
  40635. }
  40636. var i0 = this._wrapPosition(this._pos - 1.0);
  40637. return this._samples[this._wrapPosition(i0 - i)];
  40638. };
  40639. /**
  40640. * Returns true if enough samples have been taken to completely fill the sliding window
  40641. * @return true if sample-set saturated
  40642. */
  40643. RollingAverage.prototype.isSaturated = function () {
  40644. return this._sampleCount >= this._samples.length;
  40645. };
  40646. /**
  40647. * Resets the rolling average (equivalent to 0 samples taken so far)
  40648. */
  40649. RollingAverage.prototype.reset = function () {
  40650. this.average = 0;
  40651. this.variance = 0;
  40652. this._sampleCount = 0;
  40653. this._pos = 0;
  40654. this._m2 = 0;
  40655. };
  40656. /**
  40657. * Wraps a value around the sample range boundaries
  40658. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40659. * @return Wrapped position in sample range
  40660. */
  40661. RollingAverage.prototype._wrapPosition = function (i) {
  40662. var max = this._samples.length;
  40663. return ((i % max) + max) % max;
  40664. };
  40665. return RollingAverage;
  40666. }());
  40667. BABYLON.RollingAverage = RollingAverage;
  40668. })(BABYLON || (BABYLON = {}));
  40669. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40670. var BABYLON;
  40671. (function (BABYLON) {
  40672. /**
  40673. * "Static Class" containing the most commonly used helper while dealing with material for
  40674. * rendering purpose.
  40675. *
  40676. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40677. *
  40678. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40679. */
  40680. var MaterialHelper = /** @class */ (function () {
  40681. function MaterialHelper() {
  40682. }
  40683. /**
  40684. * Bind the current view position to an effect.
  40685. * @param effect The effect to be bound
  40686. * @param scene The scene the eyes position is used from
  40687. */
  40688. MaterialHelper.BindEyePosition = function (effect, scene) {
  40689. if (scene._forcedViewPosition) {
  40690. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40691. return;
  40692. }
  40693. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40694. };
  40695. /**
  40696. * Helps preparing the defines values about the UVs in used in the effect.
  40697. * UVs are shared as much as we can accross chanels in the shaders.
  40698. * @param texture The texture we are preparing the UVs for
  40699. * @param defines The defines to update
  40700. * @param key The chanel key "diffuse", "specular"... used in the shader
  40701. */
  40702. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40703. defines._needUVs = true;
  40704. defines[key] = true;
  40705. if (texture.getTextureMatrix().isIdentity(true)) {
  40706. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40707. if (texture.coordinatesIndex === 0) {
  40708. defines["MAINUV1"] = true;
  40709. }
  40710. else {
  40711. defines["MAINUV2"] = true;
  40712. }
  40713. }
  40714. else {
  40715. defines[key + "DIRECTUV"] = 0;
  40716. }
  40717. };
  40718. /**
  40719. * Binds a texture matrix value to its corrsponding uniform
  40720. * @param texture The texture to bind the matrix for
  40721. * @param uniformBuffer The uniform buffer receivin the data
  40722. * @param key The chanel key "diffuse", "specular"... used in the shader
  40723. */
  40724. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40725. var matrix = texture.getTextureMatrix();
  40726. if (!matrix.isIdentity(true)) {
  40727. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40728. }
  40729. };
  40730. /**
  40731. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40732. * @param mesh defines the current mesh
  40733. * @param scene defines the current scene
  40734. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40735. * @param pointsCloud defines if point cloud rendering has to be turned on
  40736. * @param fogEnabled defines if fog has to be turned on
  40737. * @param alphaTest defines if alpha testing has to be turned on
  40738. * @param defines defines the current list of defines
  40739. */
  40740. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40741. if (defines._areMiscDirty) {
  40742. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40743. defines["POINTSIZE"] = pointsCloud;
  40744. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40745. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40746. defines["ALPHATEST"] = alphaTest;
  40747. }
  40748. };
  40749. /**
  40750. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40751. * @param scene defines the current scene
  40752. * @param engine defines the current engine
  40753. * @param defines specifies the list of active defines
  40754. * @param useInstances defines if instances have to be turned on
  40755. * @param useClipPlane defines if clip plane have to be turned on
  40756. */
  40757. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40758. if (useClipPlane === void 0) { useClipPlane = null; }
  40759. var changed = false;
  40760. if (useClipPlane == null) {
  40761. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40762. }
  40763. if (defines["CLIPPLANE"] !== useClipPlane) {
  40764. defines["CLIPPLANE"] = useClipPlane;
  40765. changed = true;
  40766. }
  40767. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40768. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40769. changed = true;
  40770. }
  40771. if (defines["INSTANCES"] !== useInstances) {
  40772. defines["INSTANCES"] = useInstances;
  40773. changed = true;
  40774. }
  40775. if (changed) {
  40776. defines.markAsUnprocessed();
  40777. }
  40778. };
  40779. /**
  40780. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40781. * @param mesh The mesh containing the geometry data we will draw
  40782. * @param defines The defines to update
  40783. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40784. * @param useBones Precise whether bones should be used or not (override mesh info)
  40785. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40786. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40787. * @returns false if defines are considered not dirty and have not been checked
  40788. */
  40789. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40790. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40791. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40792. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40793. return false;
  40794. }
  40795. defines._normals = defines._needNormals;
  40796. defines._uvs = defines._needUVs;
  40797. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40798. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40799. defines["TANGENT"] = true;
  40800. }
  40801. if (defines._needUVs) {
  40802. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40803. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40804. }
  40805. else {
  40806. defines["UV1"] = false;
  40807. defines["UV2"] = false;
  40808. }
  40809. if (useVertexColor) {
  40810. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40811. defines["VERTEXCOLOR"] = hasVertexColors;
  40812. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40813. }
  40814. if (useBones) {
  40815. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40816. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40817. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40818. }
  40819. else {
  40820. defines["NUM_BONE_INFLUENCERS"] = 0;
  40821. defines["BonesPerMesh"] = 0;
  40822. }
  40823. }
  40824. if (useMorphTargets) {
  40825. var manager = mesh.morphTargetManager;
  40826. if (manager) {
  40827. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40828. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40829. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40830. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40831. }
  40832. else {
  40833. defines["MORPHTARGETS_TANGENT"] = false;
  40834. defines["MORPHTARGETS_NORMAL"] = false;
  40835. defines["MORPHTARGETS"] = false;
  40836. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40837. }
  40838. }
  40839. return true;
  40840. };
  40841. /**
  40842. * Prepares the defines related to the light information passed in parameter
  40843. * @param scene The scene we are intending to draw
  40844. * @param mesh The mesh the effect is compiling for
  40845. * @param defines The defines to update
  40846. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40847. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40848. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40849. * @returns true if normals will be required for the rest of the effect
  40850. */
  40851. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40852. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40853. if (disableLighting === void 0) { disableLighting = false; }
  40854. if (!defines._areLightsDirty) {
  40855. return defines._needNormals;
  40856. }
  40857. var lightIndex = 0;
  40858. var needNormals = false;
  40859. var needRebuild = false;
  40860. var lightmapMode = false;
  40861. var shadowEnabled = false;
  40862. var specularEnabled = false;
  40863. if (scene.lightsEnabled && !disableLighting) {
  40864. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40865. var light = _a[_i];
  40866. needNormals = true;
  40867. if (defines["LIGHT" + lightIndex] === undefined) {
  40868. needRebuild = true;
  40869. }
  40870. defines["LIGHT" + lightIndex] = true;
  40871. defines["SPOTLIGHT" + lightIndex] = false;
  40872. defines["HEMILIGHT" + lightIndex] = false;
  40873. defines["POINTLIGHT" + lightIndex] = false;
  40874. defines["DIRLIGHT" + lightIndex] = false;
  40875. light.prepareLightSpecificDefines(defines, lightIndex);
  40876. // Specular
  40877. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40878. specularEnabled = true;
  40879. }
  40880. // Shadows
  40881. defines["SHADOW" + lightIndex] = false;
  40882. defines["SHADOWPCF" + lightIndex] = false;
  40883. defines["SHADOWPCSS" + lightIndex] = false;
  40884. defines["SHADOWPOISSON" + lightIndex] = false;
  40885. defines["SHADOWESM" + lightIndex] = false;
  40886. defines["SHADOWCUBE" + lightIndex] = false;
  40887. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40888. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40889. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40890. var shadowGenerator = light.getShadowGenerator();
  40891. if (shadowGenerator) {
  40892. var shadowMap = shadowGenerator.getShadowMap();
  40893. if (shadowMap) {
  40894. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40895. shadowEnabled = true;
  40896. shadowGenerator.prepareDefines(defines, lightIndex);
  40897. }
  40898. }
  40899. }
  40900. }
  40901. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40902. lightmapMode = true;
  40903. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40904. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40905. }
  40906. else {
  40907. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40908. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40909. }
  40910. lightIndex++;
  40911. if (lightIndex === maxSimultaneousLights)
  40912. break;
  40913. }
  40914. }
  40915. defines["SPECULARTERM"] = specularEnabled;
  40916. defines["SHADOWS"] = shadowEnabled;
  40917. // Resetting all other lights if any
  40918. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40919. if (defines["LIGHT" + index] !== undefined) {
  40920. defines["LIGHT" + index] = false;
  40921. defines["HEMILIGHT" + lightIndex] = false;
  40922. defines["POINTLIGHT" + lightIndex] = false;
  40923. defines["DIRLIGHT" + lightIndex] = false;
  40924. defines["SPOTLIGHT" + lightIndex] = false;
  40925. defines["SHADOW" + lightIndex] = false;
  40926. }
  40927. }
  40928. var caps = scene.getEngine().getCaps();
  40929. if (defines["SHADOWFLOAT"] === undefined) {
  40930. needRebuild = true;
  40931. }
  40932. defines["SHADOWFLOAT"] = shadowEnabled &&
  40933. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40934. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40935. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40936. if (needRebuild) {
  40937. defines.rebuild();
  40938. }
  40939. return needNormals;
  40940. };
  40941. /**
  40942. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40943. * that won t be acctive due to defines being turned off.
  40944. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40945. * @param samplersList The samplers list
  40946. * @param defines The defines helping in the list generation
  40947. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40948. */
  40949. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40950. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40951. var uniformsList;
  40952. var uniformBuffersList = null;
  40953. if (uniformsListOrOptions.uniformsNames) {
  40954. var options = uniformsListOrOptions;
  40955. uniformsList = options.uniformsNames;
  40956. uniformBuffersList = options.uniformBuffersNames;
  40957. samplersList = options.samplers;
  40958. defines = options.defines;
  40959. maxSimultaneousLights = options.maxSimultaneousLights;
  40960. }
  40961. else {
  40962. uniformsList = uniformsListOrOptions;
  40963. if (!samplersList) {
  40964. samplersList = [];
  40965. }
  40966. }
  40967. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40968. if (!defines["LIGHT" + lightIndex]) {
  40969. break;
  40970. }
  40971. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40972. if (uniformBuffersList) {
  40973. uniformBuffersList.push("Light" + lightIndex);
  40974. }
  40975. samplersList.push("shadowSampler" + lightIndex);
  40976. samplersList.push("depthSampler" + lightIndex);
  40977. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40978. samplersList.push("projectionLightSampler" + lightIndex);
  40979. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40980. }
  40981. }
  40982. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40983. uniformsList.push("morphTargetInfluences");
  40984. }
  40985. };
  40986. /**
  40987. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40988. * @param defines The defines to update while falling back
  40989. * @param fallbacks The authorized effect fallbacks
  40990. * @param maxSimultaneousLights The maximum number of lights allowed
  40991. * @param rank the current rank of the Effect
  40992. * @returns The newly affected rank
  40993. */
  40994. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40995. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40996. if (rank === void 0) { rank = 0; }
  40997. var lightFallbackRank = 0;
  40998. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40999. if (!defines["LIGHT" + lightIndex]) {
  41000. break;
  41001. }
  41002. if (lightIndex > 0) {
  41003. lightFallbackRank = rank + lightIndex;
  41004. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41005. }
  41006. if (!defines["SHADOWS"]) {
  41007. if (defines["SHADOW" + lightIndex]) {
  41008. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41009. }
  41010. if (defines["SHADOWPCF" + lightIndex]) {
  41011. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41012. }
  41013. if (defines["SHADOWPCSS" + lightIndex]) {
  41014. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41015. }
  41016. if (defines["SHADOWPOISSON" + lightIndex]) {
  41017. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41018. }
  41019. if (defines["SHADOWESM" + lightIndex]) {
  41020. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41021. }
  41022. }
  41023. }
  41024. return lightFallbackRank++;
  41025. };
  41026. /**
  41027. * Prepares the list of attributes required for morph targets according to the effect defines.
  41028. * @param attribs The current list of supported attribs
  41029. * @param mesh The mesh to prepare the morph targets attributes for
  41030. * @param defines The current Defines of the effect
  41031. */
  41032. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41033. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41034. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41035. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41036. var manager = mesh.morphTargetManager;
  41037. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41038. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41039. for (var index = 0; index < influencers; index++) {
  41040. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41041. if (normal) {
  41042. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41043. }
  41044. if (tangent) {
  41045. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41046. }
  41047. if (attribs.length > maxAttributesCount) {
  41048. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41049. }
  41050. }
  41051. }
  41052. };
  41053. /**
  41054. * Prepares the list of attributes required for bones according to the effect defines.
  41055. * @param attribs The current list of supported attribs
  41056. * @param mesh The mesh to prepare the bones attributes for
  41057. * @param defines The current Defines of the effect
  41058. * @param fallbacks The current efffect fallback strategy
  41059. */
  41060. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41061. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41062. fallbacks.addCPUSkinningFallback(0, mesh);
  41063. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41064. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41065. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41066. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41067. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41068. }
  41069. }
  41070. };
  41071. /**
  41072. * Prepares the list of attributes required for instances according to the effect defines.
  41073. * @param attribs The current list of supported attribs
  41074. * @param defines The current Defines of the effect
  41075. */
  41076. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41077. if (defines["INSTANCES"]) {
  41078. attribs.push("world0");
  41079. attribs.push("world1");
  41080. attribs.push("world2");
  41081. attribs.push("world3");
  41082. }
  41083. };
  41084. /**
  41085. * Binds the light shadow information to the effect for the given mesh.
  41086. * @param light The light containing the generator
  41087. * @param scene The scene the lights belongs to
  41088. * @param mesh The mesh we are binding the information to render
  41089. * @param lightIndex The light index in the effect used to render the mesh
  41090. * @param effect The effect we are binding the data to
  41091. */
  41092. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41093. if (light.shadowEnabled && mesh.receiveShadows) {
  41094. var shadowGenerator = light.getShadowGenerator();
  41095. if (shadowGenerator) {
  41096. shadowGenerator.bindShadowLight(lightIndex, effect);
  41097. }
  41098. }
  41099. };
  41100. /**
  41101. * Binds the light information to the effect.
  41102. * @param light The light containing the generator
  41103. * @param effect The effect we are binding the data to
  41104. * @param lightIndex The light index in the effect used to render
  41105. */
  41106. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41107. light.transferToEffect(effect, lightIndex + "");
  41108. };
  41109. /**
  41110. * Binds the lights information from the scene to the effect for the given mesh.
  41111. * @param scene The scene the lights belongs to
  41112. * @param mesh The mesh we are binding the information to render
  41113. * @param effect The effect we are binding the data to
  41114. * @param defines The generated defines for the effect
  41115. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41116. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41117. */
  41118. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41119. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41120. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41121. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41122. for (var i = 0; i < len; i++) {
  41123. var light = mesh._lightSources[i];
  41124. var iAsString = i.toString();
  41125. var scaledIntensity = light.getScaledIntensity();
  41126. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41127. MaterialHelper.BindLightProperties(light, effect, i);
  41128. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41129. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41130. if (defines["SPECULARTERM"]) {
  41131. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41132. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41133. }
  41134. // Shadows
  41135. if (scene.shadowsEnabled) {
  41136. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41137. }
  41138. light._uniformBuffer.update();
  41139. }
  41140. };
  41141. /**
  41142. * Binds the fog information from the scene to the effect for the given mesh.
  41143. * @param scene The scene the lights belongs to
  41144. * @param mesh The mesh we are binding the information to render
  41145. * @param effect The effect we are binding the data to
  41146. */
  41147. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41148. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41149. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41150. effect.setColor3("vFogColor", scene.fogColor);
  41151. }
  41152. };
  41153. /**
  41154. * Binds the bones information from the mesh to the effect.
  41155. * @param mesh The mesh we are binding the information to render
  41156. * @param effect The effect we are binding the data to
  41157. */
  41158. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41159. if (!effect || !mesh) {
  41160. return;
  41161. }
  41162. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41163. mesh.computeBonesUsingShaders = false;
  41164. }
  41165. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41166. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41167. if (matrices) {
  41168. effect.setMatrices("mBones", matrices);
  41169. }
  41170. }
  41171. };
  41172. /**
  41173. * Binds the morph targets information from the mesh to the effect.
  41174. * @param abstractMesh The mesh we are binding the information to render
  41175. * @param effect The effect we are binding the data to
  41176. */
  41177. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41178. var manager = abstractMesh.morphTargetManager;
  41179. if (!abstractMesh || !manager) {
  41180. return;
  41181. }
  41182. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41183. };
  41184. /**
  41185. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41186. * @param defines The generated defines used in the effect
  41187. * @param effect The effect we are binding the data to
  41188. * @param scene The scene we are willing to render with logarithmic scale for
  41189. */
  41190. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41191. if (defines["LOGARITHMICDEPTH"]) {
  41192. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41193. }
  41194. };
  41195. /**
  41196. * Binds the clip plane information from the scene to the effect.
  41197. * @param scene The scene the clip plane information are extracted from
  41198. * @param effect The effect we are binding the data to
  41199. */
  41200. MaterialHelper.BindClipPlane = function (effect, scene) {
  41201. if (scene.clipPlane) {
  41202. var clipPlane = scene.clipPlane;
  41203. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41204. }
  41205. };
  41206. return MaterialHelper;
  41207. }());
  41208. BABYLON.MaterialHelper = MaterialHelper;
  41209. })(BABYLON || (BABYLON = {}));
  41210. //# sourceMappingURL=babylon.materialHelper.js.map
  41211. var BABYLON;
  41212. (function (BABYLON) {
  41213. var PushMaterial = /** @class */ (function (_super) {
  41214. __extends(PushMaterial, _super);
  41215. function PushMaterial(name, scene) {
  41216. var _this = _super.call(this, name, scene) || this;
  41217. _this._normalMatrix = new BABYLON.Matrix();
  41218. _this.storeEffectOnSubMeshes = true;
  41219. return _this;
  41220. }
  41221. PushMaterial.prototype.getEffect = function () {
  41222. return this._activeEffect;
  41223. };
  41224. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41225. if (!mesh) {
  41226. return false;
  41227. }
  41228. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41229. return true;
  41230. }
  41231. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41232. };
  41233. /**
  41234. * Binds the given world matrix to the active effect
  41235. *
  41236. * @param world the matrix to bind
  41237. */
  41238. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41239. this._activeEffect.setMatrix("world", world);
  41240. };
  41241. /**
  41242. * Binds the given normal matrix to the active effect
  41243. *
  41244. * @param normalMatrix the matrix to bind
  41245. */
  41246. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41247. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41248. };
  41249. PushMaterial.prototype.bind = function (world, mesh) {
  41250. if (!mesh) {
  41251. return;
  41252. }
  41253. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41254. };
  41255. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41256. if (effect === void 0) { effect = null; }
  41257. _super.prototype._afterBind.call(this, mesh);
  41258. this.getScene()._cachedEffect = effect;
  41259. };
  41260. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41261. if (visibility === void 0) { visibility = 1; }
  41262. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41263. };
  41264. return PushMaterial;
  41265. }(BABYLON.Material));
  41266. BABYLON.PushMaterial = PushMaterial;
  41267. })(BABYLON || (BABYLON = {}));
  41268. //# sourceMappingURL=babylon.pushMaterial.js.map
  41269. var BABYLON;
  41270. (function (BABYLON) {
  41271. /** @hidden */
  41272. var StandardMaterialDefines = /** @class */ (function (_super) {
  41273. __extends(StandardMaterialDefines, _super);
  41274. function StandardMaterialDefines() {
  41275. var _this = _super.call(this) || this;
  41276. _this.MAINUV1 = false;
  41277. _this.MAINUV2 = false;
  41278. _this.DIFFUSE = false;
  41279. _this.DIFFUSEDIRECTUV = 0;
  41280. _this.AMBIENT = false;
  41281. _this.AMBIENTDIRECTUV = 0;
  41282. _this.OPACITY = false;
  41283. _this.OPACITYDIRECTUV = 0;
  41284. _this.OPACITYRGB = false;
  41285. _this.REFLECTION = false;
  41286. _this.EMISSIVE = false;
  41287. _this.EMISSIVEDIRECTUV = 0;
  41288. _this.SPECULAR = false;
  41289. _this.SPECULARDIRECTUV = 0;
  41290. _this.BUMP = false;
  41291. _this.BUMPDIRECTUV = 0;
  41292. _this.PARALLAX = false;
  41293. _this.PARALLAXOCCLUSION = false;
  41294. _this.SPECULAROVERALPHA = false;
  41295. _this.CLIPPLANE = false;
  41296. _this.ALPHATEST = false;
  41297. _this.DEPTHPREPASS = false;
  41298. _this.ALPHAFROMDIFFUSE = false;
  41299. _this.POINTSIZE = false;
  41300. _this.FOG = false;
  41301. _this.SPECULARTERM = false;
  41302. _this.DIFFUSEFRESNEL = false;
  41303. _this.OPACITYFRESNEL = false;
  41304. _this.REFLECTIONFRESNEL = false;
  41305. _this.REFRACTIONFRESNEL = false;
  41306. _this.EMISSIVEFRESNEL = false;
  41307. _this.FRESNEL = false;
  41308. _this.NORMAL = false;
  41309. _this.UV1 = false;
  41310. _this.UV2 = false;
  41311. _this.VERTEXCOLOR = false;
  41312. _this.VERTEXALPHA = false;
  41313. _this.NUM_BONE_INFLUENCERS = 0;
  41314. _this.BonesPerMesh = 0;
  41315. _this.INSTANCES = false;
  41316. _this.GLOSSINESS = false;
  41317. _this.ROUGHNESS = false;
  41318. _this.EMISSIVEASILLUMINATION = false;
  41319. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41320. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41321. _this.LIGHTMAP = false;
  41322. _this.LIGHTMAPDIRECTUV = 0;
  41323. _this.OBJECTSPACE_NORMALMAP = false;
  41324. _this.USELIGHTMAPASSHADOWMAP = false;
  41325. _this.REFLECTIONMAP_3D = false;
  41326. _this.REFLECTIONMAP_SPHERICAL = false;
  41327. _this.REFLECTIONMAP_PLANAR = false;
  41328. _this.REFLECTIONMAP_CUBIC = false;
  41329. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41330. _this.REFLECTIONMAP_PROJECTION = false;
  41331. _this.REFLECTIONMAP_SKYBOX = false;
  41332. _this.REFLECTIONMAP_EXPLICIT = false;
  41333. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41334. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41335. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41336. _this.INVERTCUBICMAP = false;
  41337. _this.LOGARITHMICDEPTH = false;
  41338. _this.REFRACTION = false;
  41339. _this.REFRACTIONMAP_3D = false;
  41340. _this.REFLECTIONOVERALPHA = false;
  41341. _this.TWOSIDEDLIGHTING = false;
  41342. _this.SHADOWFLOAT = false;
  41343. _this.MORPHTARGETS = false;
  41344. _this.MORPHTARGETS_NORMAL = false;
  41345. _this.MORPHTARGETS_TANGENT = false;
  41346. _this.NUM_MORPH_INFLUENCERS = 0;
  41347. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41348. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41349. _this.IMAGEPROCESSING = false;
  41350. _this.VIGNETTE = false;
  41351. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41352. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41353. _this.TONEMAPPING = false;
  41354. _this.CONTRAST = false;
  41355. _this.COLORCURVES = false;
  41356. _this.COLORGRADING = false;
  41357. _this.COLORGRADING3D = false;
  41358. _this.SAMPLER3DGREENDEPTH = false;
  41359. _this.SAMPLER3DBGRMAP = false;
  41360. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41361. /**
  41362. * If the reflection texture on this material is in linear color space
  41363. * @hidden
  41364. */
  41365. _this.IS_REFLECTION_LINEAR = false;
  41366. /**
  41367. * If the refraction texture on this material is in linear color space
  41368. * @hidden
  41369. */
  41370. _this.IS_REFRACTION_LINEAR = false;
  41371. _this.EXPOSURE = false;
  41372. _this.rebuild();
  41373. return _this;
  41374. }
  41375. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41376. var modes = [
  41377. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41378. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41379. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41380. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41381. ];
  41382. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41383. var mode = modes_1[_i];
  41384. this[mode] = (mode === modeToEnable);
  41385. }
  41386. };
  41387. return StandardMaterialDefines;
  41388. }(BABYLON.MaterialDefines));
  41389. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41390. var StandardMaterial = /** @class */ (function (_super) {
  41391. __extends(StandardMaterial, _super);
  41392. function StandardMaterial(name, scene) {
  41393. var _this = _super.call(this, name, scene) || this;
  41394. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41395. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41396. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41397. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41398. _this.specularPower = 64;
  41399. _this._useAlphaFromDiffuseTexture = false;
  41400. _this._useEmissiveAsIllumination = false;
  41401. _this._linkEmissiveWithDiffuse = false;
  41402. _this._useSpecularOverAlpha = false;
  41403. _this._useReflectionOverAlpha = false;
  41404. _this._disableLighting = false;
  41405. _this._useObjectSpaceNormalMap = false;
  41406. _this._useParallax = false;
  41407. _this._useParallaxOcclusion = false;
  41408. _this.parallaxScaleBias = 0.05;
  41409. _this._roughness = 0;
  41410. _this.indexOfRefraction = 0.98;
  41411. _this.invertRefractionY = true;
  41412. /**
  41413. * Defines the alpha limits in alpha test mode
  41414. */
  41415. _this.alphaCutOff = 0.4;
  41416. _this._useLightmapAsShadowmap = false;
  41417. _this._useReflectionFresnelFromSpecular = false;
  41418. _this._useGlossinessFromSpecularMapAlpha = false;
  41419. _this._maxSimultaneousLights = 4;
  41420. /**
  41421. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41422. */
  41423. _this._invertNormalMapX = false;
  41424. /**
  41425. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41426. */
  41427. _this._invertNormalMapY = false;
  41428. /**
  41429. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41430. */
  41431. _this._twoSidedLighting = false;
  41432. _this._renderTargets = new BABYLON.SmartArray(16);
  41433. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41434. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41435. // Setup the default processing configuration to the scene.
  41436. _this._attachImageProcessingConfiguration(null);
  41437. _this.getRenderTargetTextures = function () {
  41438. _this._renderTargets.reset();
  41439. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41440. _this._renderTargets.push(_this._reflectionTexture);
  41441. }
  41442. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41443. _this._renderTargets.push(_this._refractionTexture);
  41444. }
  41445. return _this._renderTargets;
  41446. };
  41447. return _this;
  41448. }
  41449. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41450. /**
  41451. * Gets the image processing configuration used either in this material.
  41452. */
  41453. get: function () {
  41454. return this._imageProcessingConfiguration;
  41455. },
  41456. /**
  41457. * Sets the Default image processing configuration used either in the this material.
  41458. *
  41459. * If sets to null, the scene one is in use.
  41460. */
  41461. set: function (value) {
  41462. this._attachImageProcessingConfiguration(value);
  41463. // Ensure the effect will be rebuilt.
  41464. this._markAllSubMeshesAsTexturesDirty();
  41465. },
  41466. enumerable: true,
  41467. configurable: true
  41468. });
  41469. /**
  41470. * Attaches a new image processing configuration to the Standard Material.
  41471. * @param configuration
  41472. */
  41473. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41474. var _this = this;
  41475. if (configuration === this._imageProcessingConfiguration) {
  41476. return;
  41477. }
  41478. // Detaches observer.
  41479. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41480. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41481. }
  41482. // Pick the scene configuration if needed.
  41483. if (!configuration) {
  41484. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41485. }
  41486. else {
  41487. this._imageProcessingConfiguration = configuration;
  41488. }
  41489. // Attaches observer.
  41490. if (this._imageProcessingConfiguration) {
  41491. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41492. _this._markAllSubMeshesAsImageProcessingDirty();
  41493. });
  41494. }
  41495. };
  41496. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41497. /**
  41498. * Gets wether the color curves effect is enabled.
  41499. */
  41500. get: function () {
  41501. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41502. },
  41503. /**
  41504. * Sets wether the color curves effect is enabled.
  41505. */
  41506. set: function (value) {
  41507. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41508. },
  41509. enumerable: true,
  41510. configurable: true
  41511. });
  41512. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41513. /**
  41514. * Gets wether the color grading effect is enabled.
  41515. */
  41516. get: function () {
  41517. return this.imageProcessingConfiguration.colorGradingEnabled;
  41518. },
  41519. /**
  41520. * Gets wether the color grading effect is enabled.
  41521. */
  41522. set: function (value) {
  41523. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41529. /**
  41530. * Gets wether tonemapping is enabled or not.
  41531. */
  41532. get: function () {
  41533. return this._imageProcessingConfiguration.toneMappingEnabled;
  41534. },
  41535. /**
  41536. * Sets wether tonemapping is enabled or not
  41537. */
  41538. set: function (value) {
  41539. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41540. },
  41541. enumerable: true,
  41542. configurable: true
  41543. });
  41544. ;
  41545. ;
  41546. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41547. /**
  41548. * The camera exposure used on this material.
  41549. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41550. * This corresponds to a photographic exposure.
  41551. */
  41552. get: function () {
  41553. return this._imageProcessingConfiguration.exposure;
  41554. },
  41555. /**
  41556. * The camera exposure used on this material.
  41557. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41558. * This corresponds to a photographic exposure.
  41559. */
  41560. set: function (value) {
  41561. this._imageProcessingConfiguration.exposure = value;
  41562. },
  41563. enumerable: true,
  41564. configurable: true
  41565. });
  41566. ;
  41567. ;
  41568. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41569. /**
  41570. * Gets The camera contrast used on this material.
  41571. */
  41572. get: function () {
  41573. return this._imageProcessingConfiguration.contrast;
  41574. },
  41575. /**
  41576. * Sets The camera contrast used on this material.
  41577. */
  41578. set: function (value) {
  41579. this._imageProcessingConfiguration.contrast = value;
  41580. },
  41581. enumerable: true,
  41582. configurable: true
  41583. });
  41584. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41585. /**
  41586. * Gets the Color Grading 2D Lookup Texture.
  41587. */
  41588. get: function () {
  41589. return this._imageProcessingConfiguration.colorGradingTexture;
  41590. },
  41591. /**
  41592. * Sets the Color Grading 2D Lookup Texture.
  41593. */
  41594. set: function (value) {
  41595. this._imageProcessingConfiguration.colorGradingTexture = value;
  41596. },
  41597. enumerable: true,
  41598. configurable: true
  41599. });
  41600. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41601. /**
  41602. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41603. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41604. * 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;
  41605. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41606. */
  41607. get: function () {
  41608. return this._imageProcessingConfiguration.colorCurves;
  41609. },
  41610. /**
  41611. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41612. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41613. * 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;
  41614. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41615. */
  41616. set: function (value) {
  41617. this._imageProcessingConfiguration.colorCurves = value;
  41618. },
  41619. enumerable: true,
  41620. configurable: true
  41621. });
  41622. StandardMaterial.prototype.getClassName = function () {
  41623. return "StandardMaterial";
  41624. };
  41625. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41626. get: function () {
  41627. return this._useLogarithmicDepth;
  41628. },
  41629. set: function (value) {
  41630. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41631. this._markAllSubMeshesAsMiscDirty();
  41632. },
  41633. enumerable: true,
  41634. configurable: true
  41635. });
  41636. StandardMaterial.prototype.needAlphaBlending = function () {
  41637. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41638. };
  41639. StandardMaterial.prototype.needAlphaTesting = function () {
  41640. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41641. };
  41642. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41643. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41644. };
  41645. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41646. return this._diffuseTexture;
  41647. };
  41648. /**
  41649. * Child classes can use it to update shaders
  41650. */
  41651. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41652. if (useInstances === void 0) { useInstances = false; }
  41653. if (subMesh.effect && this.isFrozen) {
  41654. if (this._wasPreviouslyReady && subMesh.effect) {
  41655. return true;
  41656. }
  41657. }
  41658. if (!subMesh._materialDefines) {
  41659. subMesh._materialDefines = new StandardMaterialDefines();
  41660. }
  41661. var scene = this.getScene();
  41662. var defines = subMesh._materialDefines;
  41663. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41664. if (defines._renderId === scene.getRenderId()) {
  41665. return true;
  41666. }
  41667. }
  41668. var engine = scene.getEngine();
  41669. // Lights
  41670. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41671. // Textures
  41672. if (defines._areTexturesDirty) {
  41673. defines._needUVs = false;
  41674. defines.MAINUV1 = false;
  41675. defines.MAINUV2 = false;
  41676. if (scene.texturesEnabled) {
  41677. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41678. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41679. return false;
  41680. }
  41681. else {
  41682. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41683. }
  41684. }
  41685. else {
  41686. defines.DIFFUSE = false;
  41687. }
  41688. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41689. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41690. return false;
  41691. }
  41692. else {
  41693. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41694. }
  41695. }
  41696. else {
  41697. defines.AMBIENT = false;
  41698. }
  41699. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41700. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41701. return false;
  41702. }
  41703. else {
  41704. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41705. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41706. }
  41707. }
  41708. else {
  41709. defines.OPACITY = false;
  41710. }
  41711. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41712. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41713. return false;
  41714. }
  41715. else {
  41716. defines._needNormals = true;
  41717. defines.REFLECTION = true;
  41718. defines.ROUGHNESS = (this._roughness > 0);
  41719. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41720. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41721. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41722. switch (this._reflectionTexture.coordinatesMode) {
  41723. case BABYLON.Texture.EXPLICIT_MODE:
  41724. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41725. break;
  41726. case BABYLON.Texture.PLANAR_MODE:
  41727. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41728. break;
  41729. case BABYLON.Texture.PROJECTION_MODE:
  41730. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41731. break;
  41732. case BABYLON.Texture.SKYBOX_MODE:
  41733. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41734. break;
  41735. case BABYLON.Texture.SPHERICAL_MODE:
  41736. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41737. break;
  41738. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41739. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41740. break;
  41741. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41742. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41743. break;
  41744. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41745. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41746. break;
  41747. case BABYLON.Texture.CUBIC_MODE:
  41748. case BABYLON.Texture.INVCUBIC_MODE:
  41749. default:
  41750. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41751. break;
  41752. }
  41753. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41754. }
  41755. }
  41756. else {
  41757. defines.REFLECTION = false;
  41758. }
  41759. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41760. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41761. return false;
  41762. }
  41763. else {
  41764. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41765. }
  41766. }
  41767. else {
  41768. defines.EMISSIVE = false;
  41769. }
  41770. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41771. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41772. return false;
  41773. }
  41774. else {
  41775. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41776. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41777. }
  41778. }
  41779. else {
  41780. defines.LIGHTMAP = false;
  41781. }
  41782. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41783. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41784. return false;
  41785. }
  41786. else {
  41787. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41788. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41789. }
  41790. }
  41791. else {
  41792. defines.SPECULAR = false;
  41793. }
  41794. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41795. // Bump texure can not be not blocking.
  41796. if (!this._bumpTexture.isReady()) {
  41797. return false;
  41798. }
  41799. else {
  41800. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41801. defines.PARALLAX = this._useParallax;
  41802. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41803. }
  41804. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41805. }
  41806. else {
  41807. defines.BUMP = false;
  41808. }
  41809. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41810. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41811. return false;
  41812. }
  41813. else {
  41814. defines._needUVs = true;
  41815. defines.REFRACTION = true;
  41816. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41817. }
  41818. }
  41819. else {
  41820. defines.REFRACTION = false;
  41821. }
  41822. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41823. }
  41824. else {
  41825. defines.DIFFUSE = false;
  41826. defines.AMBIENT = false;
  41827. defines.OPACITY = false;
  41828. defines.REFLECTION = false;
  41829. defines.EMISSIVE = false;
  41830. defines.LIGHTMAP = false;
  41831. defines.BUMP = false;
  41832. defines.REFRACTION = false;
  41833. }
  41834. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41835. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41836. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41837. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41838. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41839. }
  41840. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41841. if (!this._imageProcessingConfiguration.isReady()) {
  41842. return false;
  41843. }
  41844. this._imageProcessingConfiguration.prepareDefines(defines);
  41845. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41846. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41847. }
  41848. if (defines._areFresnelDirty) {
  41849. if (StandardMaterial.FresnelEnabled) {
  41850. // Fresnel
  41851. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41852. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41853. this._reflectionFresnelParameters) {
  41854. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41855. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41856. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41857. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41858. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41859. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41860. defines._needNormals = true;
  41861. defines.FRESNEL = true;
  41862. }
  41863. }
  41864. else {
  41865. defines.FRESNEL = false;
  41866. }
  41867. }
  41868. // Misc.
  41869. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41870. // Attribs
  41871. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41872. // Values that need to be evaluated on every frame
  41873. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41874. // Get correct effect
  41875. if (defines.isDirty) {
  41876. defines.markAsProcessed();
  41877. scene.resetCachedMaterial();
  41878. // Fallbacks
  41879. var fallbacks = new BABYLON.EffectFallbacks();
  41880. if (defines.REFLECTION) {
  41881. fallbacks.addFallback(0, "REFLECTION");
  41882. }
  41883. if (defines.SPECULAR) {
  41884. fallbacks.addFallback(0, "SPECULAR");
  41885. }
  41886. if (defines.BUMP) {
  41887. fallbacks.addFallback(0, "BUMP");
  41888. }
  41889. if (defines.PARALLAX) {
  41890. fallbacks.addFallback(1, "PARALLAX");
  41891. }
  41892. if (defines.PARALLAXOCCLUSION) {
  41893. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41894. }
  41895. if (defines.SPECULAROVERALPHA) {
  41896. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41897. }
  41898. if (defines.FOG) {
  41899. fallbacks.addFallback(1, "FOG");
  41900. }
  41901. if (defines.POINTSIZE) {
  41902. fallbacks.addFallback(0, "POINTSIZE");
  41903. }
  41904. if (defines.LOGARITHMICDEPTH) {
  41905. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41906. }
  41907. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41908. if (defines.SPECULARTERM) {
  41909. fallbacks.addFallback(0, "SPECULARTERM");
  41910. }
  41911. if (defines.DIFFUSEFRESNEL) {
  41912. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41913. }
  41914. if (defines.OPACITYFRESNEL) {
  41915. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41916. }
  41917. if (defines.REFLECTIONFRESNEL) {
  41918. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41919. }
  41920. if (defines.EMISSIVEFRESNEL) {
  41921. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41922. }
  41923. if (defines.FRESNEL) {
  41924. fallbacks.addFallback(4, "FRESNEL");
  41925. }
  41926. //Attributes
  41927. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41928. if (defines.NORMAL) {
  41929. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41930. }
  41931. if (defines.UV1) {
  41932. attribs.push(BABYLON.VertexBuffer.UVKind);
  41933. }
  41934. if (defines.UV2) {
  41935. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41936. }
  41937. if (defines.VERTEXCOLOR) {
  41938. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41939. }
  41940. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41941. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41942. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41943. var shaderName = "default";
  41944. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41945. "vFogInfos", "vFogColor", "pointSize",
  41946. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41947. "mBones",
  41948. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41949. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41950. "vReflectionPosition", "vReflectionSize",
  41951. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41952. ];
  41953. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41954. var uniformBuffers = ["Material", "Scene"];
  41955. if (BABYLON.ImageProcessingConfiguration) {
  41956. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41957. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41958. }
  41959. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41960. uniformsNames: uniforms,
  41961. uniformBuffersNames: uniformBuffers,
  41962. samplers: samplers,
  41963. defines: defines,
  41964. maxSimultaneousLights: this._maxSimultaneousLights
  41965. });
  41966. if (this.customShaderNameResolve) {
  41967. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41968. }
  41969. var join = defines.toString();
  41970. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41971. attributes: attribs,
  41972. uniformsNames: uniforms,
  41973. uniformBuffersNames: uniformBuffers,
  41974. samplers: samplers,
  41975. defines: join,
  41976. fallbacks: fallbacks,
  41977. onCompiled: this.onCompiled,
  41978. onError: this.onError,
  41979. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41980. }, engine), defines);
  41981. this.buildUniformLayout();
  41982. }
  41983. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41984. return false;
  41985. }
  41986. defines._renderId = scene.getRenderId();
  41987. this._wasPreviouslyReady = true;
  41988. return true;
  41989. };
  41990. StandardMaterial.prototype.buildUniformLayout = function () {
  41991. // Order is important !
  41992. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41993. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41994. this._uniformBuffer.addUniform("opacityParts", 4);
  41995. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41996. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41997. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41998. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41999. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42000. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42001. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42002. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42003. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42004. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42005. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42006. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42007. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42008. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42009. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42010. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42011. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42012. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42013. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42014. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42015. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42016. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42017. this._uniformBuffer.addUniform("specularMatrix", 16);
  42018. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42019. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42020. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42021. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42022. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42023. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42024. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42025. this._uniformBuffer.addUniform("pointSize", 1);
  42026. this._uniformBuffer.create();
  42027. };
  42028. StandardMaterial.prototype.unbind = function () {
  42029. if (this._activeEffect) {
  42030. var needFlag = false;
  42031. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42032. this._activeEffect.setTexture("reflection2DSampler", null);
  42033. needFlag = true;
  42034. }
  42035. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42036. this._activeEffect.setTexture("refraction2DSampler", null);
  42037. needFlag = true;
  42038. }
  42039. if (needFlag) {
  42040. this._markAllSubMeshesAsTexturesDirty();
  42041. }
  42042. }
  42043. _super.prototype.unbind.call(this);
  42044. };
  42045. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42046. var scene = this.getScene();
  42047. var defines = subMesh._materialDefines;
  42048. if (!defines) {
  42049. return;
  42050. }
  42051. var effect = subMesh.effect;
  42052. if (!effect) {
  42053. return;
  42054. }
  42055. this._activeEffect = effect;
  42056. // Matrices
  42057. this.bindOnlyWorldMatrix(world);
  42058. // Normal Matrix
  42059. if (defines.OBJECTSPACE_NORMALMAP) {
  42060. world.toNormalMatrix(this._normalMatrix);
  42061. this.bindOnlyNormalMatrix(this._normalMatrix);
  42062. }
  42063. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42064. // Bones
  42065. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42066. if (mustRebind) {
  42067. this._uniformBuffer.bindToEffect(effect, "Material");
  42068. this.bindViewProjection(effect);
  42069. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42070. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42071. // Fresnel
  42072. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42073. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42074. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42075. }
  42076. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42077. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42078. }
  42079. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42080. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42081. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42082. }
  42083. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42084. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42085. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42086. }
  42087. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42088. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42089. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42090. }
  42091. }
  42092. // Textures
  42093. if (scene.texturesEnabled) {
  42094. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42095. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42096. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42097. if (this._diffuseTexture.hasAlpha) {
  42098. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42099. }
  42100. }
  42101. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42102. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42103. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42104. }
  42105. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42106. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42107. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42108. }
  42109. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42110. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42111. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42112. if (this._reflectionTexture.boundingBoxSize) {
  42113. var cubeTexture = this._reflectionTexture;
  42114. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42115. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42116. }
  42117. }
  42118. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42119. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42120. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42121. }
  42122. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42123. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42124. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42125. }
  42126. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42127. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42128. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42129. }
  42130. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42131. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42132. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42133. if (scene._mirroredCameraPosition) {
  42134. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42135. }
  42136. else {
  42137. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42138. }
  42139. }
  42140. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42141. var depth = 1.0;
  42142. if (!this._refractionTexture.isCube) {
  42143. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42144. if (this._refractionTexture.depth) {
  42145. depth = this._refractionTexture.depth;
  42146. }
  42147. }
  42148. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42149. }
  42150. }
  42151. // Point size
  42152. if (this.pointsCloud) {
  42153. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42154. }
  42155. if (defines.SPECULARTERM) {
  42156. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42157. }
  42158. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42159. // Diffuse
  42160. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42161. }
  42162. // Textures
  42163. if (scene.texturesEnabled) {
  42164. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42165. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42166. }
  42167. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42168. effect.setTexture("ambientSampler", this._ambientTexture);
  42169. }
  42170. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42171. effect.setTexture("opacitySampler", this._opacityTexture);
  42172. }
  42173. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42174. if (this._reflectionTexture.isCube) {
  42175. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42176. }
  42177. else {
  42178. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42179. }
  42180. }
  42181. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42182. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42183. }
  42184. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42185. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42186. }
  42187. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42188. effect.setTexture("specularSampler", this._specularTexture);
  42189. }
  42190. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42191. effect.setTexture("bumpSampler", this._bumpTexture);
  42192. }
  42193. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42194. var depth = 1.0;
  42195. if (this._refractionTexture.isCube) {
  42196. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42197. }
  42198. else {
  42199. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42200. }
  42201. }
  42202. }
  42203. // Clip plane
  42204. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42205. // Colors
  42206. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42207. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42208. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42209. }
  42210. if (mustRebind || !this.isFrozen) {
  42211. // Lights
  42212. if (scene.lightsEnabled && !this._disableLighting) {
  42213. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42214. }
  42215. // View
  42216. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42217. this.bindView(effect);
  42218. }
  42219. // Fog
  42220. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42221. // Morph targets
  42222. if (defines.NUM_MORPH_INFLUENCERS) {
  42223. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42224. }
  42225. // Log. depth
  42226. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42227. // image processing
  42228. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42229. this._imageProcessingConfiguration.bind(this._activeEffect);
  42230. }
  42231. }
  42232. this._uniformBuffer.update();
  42233. this._afterBind(mesh, this._activeEffect);
  42234. };
  42235. StandardMaterial.prototype.getAnimatables = function () {
  42236. var results = [];
  42237. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42238. results.push(this._diffuseTexture);
  42239. }
  42240. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42241. results.push(this._ambientTexture);
  42242. }
  42243. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42244. results.push(this._opacityTexture);
  42245. }
  42246. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42247. results.push(this._reflectionTexture);
  42248. }
  42249. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42250. results.push(this._emissiveTexture);
  42251. }
  42252. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42253. results.push(this._specularTexture);
  42254. }
  42255. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42256. results.push(this._bumpTexture);
  42257. }
  42258. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42259. results.push(this._lightmapTexture);
  42260. }
  42261. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42262. results.push(this._refractionTexture);
  42263. }
  42264. return results;
  42265. };
  42266. StandardMaterial.prototype.getActiveTextures = function () {
  42267. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42268. if (this._diffuseTexture) {
  42269. activeTextures.push(this._diffuseTexture);
  42270. }
  42271. if (this._ambientTexture) {
  42272. activeTextures.push(this._ambientTexture);
  42273. }
  42274. if (this._opacityTexture) {
  42275. activeTextures.push(this._opacityTexture);
  42276. }
  42277. if (this._reflectionTexture) {
  42278. activeTextures.push(this._reflectionTexture);
  42279. }
  42280. if (this._emissiveTexture) {
  42281. activeTextures.push(this._emissiveTexture);
  42282. }
  42283. if (this._specularTexture) {
  42284. activeTextures.push(this._specularTexture);
  42285. }
  42286. if (this._bumpTexture) {
  42287. activeTextures.push(this._bumpTexture);
  42288. }
  42289. if (this._lightmapTexture) {
  42290. activeTextures.push(this._lightmapTexture);
  42291. }
  42292. if (this._refractionTexture) {
  42293. activeTextures.push(this._refractionTexture);
  42294. }
  42295. return activeTextures;
  42296. };
  42297. StandardMaterial.prototype.hasTexture = function (texture) {
  42298. if (_super.prototype.hasTexture.call(this, texture)) {
  42299. return true;
  42300. }
  42301. if (this._diffuseTexture === texture) {
  42302. return true;
  42303. }
  42304. if (this._ambientTexture === texture) {
  42305. return true;
  42306. }
  42307. if (this._opacityTexture === texture) {
  42308. return true;
  42309. }
  42310. if (this._reflectionTexture === texture) {
  42311. return true;
  42312. }
  42313. if (this._emissiveTexture === texture) {
  42314. return true;
  42315. }
  42316. if (this._specularTexture === texture) {
  42317. return true;
  42318. }
  42319. if (this._bumpTexture === texture) {
  42320. return true;
  42321. }
  42322. if (this._lightmapTexture === texture) {
  42323. return true;
  42324. }
  42325. if (this._refractionTexture === texture) {
  42326. return true;
  42327. }
  42328. return false;
  42329. };
  42330. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42331. if (forceDisposeTextures) {
  42332. if (this._diffuseTexture) {
  42333. this._diffuseTexture.dispose();
  42334. }
  42335. if (this._ambientTexture) {
  42336. this._ambientTexture.dispose();
  42337. }
  42338. if (this._opacityTexture) {
  42339. this._opacityTexture.dispose();
  42340. }
  42341. if (this._reflectionTexture) {
  42342. this._reflectionTexture.dispose();
  42343. }
  42344. if (this._emissiveTexture) {
  42345. this._emissiveTexture.dispose();
  42346. }
  42347. if (this._specularTexture) {
  42348. this._specularTexture.dispose();
  42349. }
  42350. if (this._bumpTexture) {
  42351. this._bumpTexture.dispose();
  42352. }
  42353. if (this._lightmapTexture) {
  42354. this._lightmapTexture.dispose();
  42355. }
  42356. if (this._refractionTexture) {
  42357. this._refractionTexture.dispose();
  42358. }
  42359. }
  42360. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42361. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42362. }
  42363. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42364. };
  42365. StandardMaterial.prototype.clone = function (name) {
  42366. var _this = this;
  42367. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42368. result.name = name;
  42369. result.id = name;
  42370. return result;
  42371. };
  42372. StandardMaterial.prototype.serialize = function () {
  42373. return BABYLON.SerializationHelper.Serialize(this);
  42374. };
  42375. // Statics
  42376. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42377. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42378. };
  42379. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42380. get: function () {
  42381. return StandardMaterial._DiffuseTextureEnabled;
  42382. },
  42383. set: function (value) {
  42384. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42385. return;
  42386. }
  42387. StandardMaterial._DiffuseTextureEnabled = value;
  42388. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42389. },
  42390. enumerable: true,
  42391. configurable: true
  42392. });
  42393. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42394. get: function () {
  42395. return StandardMaterial._AmbientTextureEnabled;
  42396. },
  42397. set: function (value) {
  42398. if (StandardMaterial._AmbientTextureEnabled === value) {
  42399. return;
  42400. }
  42401. StandardMaterial._AmbientTextureEnabled = value;
  42402. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42403. },
  42404. enumerable: true,
  42405. configurable: true
  42406. });
  42407. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42408. get: function () {
  42409. return StandardMaterial._OpacityTextureEnabled;
  42410. },
  42411. set: function (value) {
  42412. if (StandardMaterial._OpacityTextureEnabled === value) {
  42413. return;
  42414. }
  42415. StandardMaterial._OpacityTextureEnabled = value;
  42416. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42422. get: function () {
  42423. return StandardMaterial._ReflectionTextureEnabled;
  42424. },
  42425. set: function (value) {
  42426. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42427. return;
  42428. }
  42429. StandardMaterial._ReflectionTextureEnabled = value;
  42430. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42436. get: function () {
  42437. return StandardMaterial._EmissiveTextureEnabled;
  42438. },
  42439. set: function (value) {
  42440. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42441. return;
  42442. }
  42443. StandardMaterial._EmissiveTextureEnabled = value;
  42444. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42445. },
  42446. enumerable: true,
  42447. configurable: true
  42448. });
  42449. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42450. get: function () {
  42451. return StandardMaterial._SpecularTextureEnabled;
  42452. },
  42453. set: function (value) {
  42454. if (StandardMaterial._SpecularTextureEnabled === value) {
  42455. return;
  42456. }
  42457. StandardMaterial._SpecularTextureEnabled = value;
  42458. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42459. },
  42460. enumerable: true,
  42461. configurable: true
  42462. });
  42463. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42464. get: function () {
  42465. return StandardMaterial._BumpTextureEnabled;
  42466. },
  42467. set: function (value) {
  42468. if (StandardMaterial._BumpTextureEnabled === value) {
  42469. return;
  42470. }
  42471. StandardMaterial._BumpTextureEnabled = value;
  42472. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42473. },
  42474. enumerable: true,
  42475. configurable: true
  42476. });
  42477. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42478. get: function () {
  42479. return StandardMaterial._LightmapTextureEnabled;
  42480. },
  42481. set: function (value) {
  42482. if (StandardMaterial._LightmapTextureEnabled === value) {
  42483. return;
  42484. }
  42485. StandardMaterial._LightmapTextureEnabled = value;
  42486. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42487. },
  42488. enumerable: true,
  42489. configurable: true
  42490. });
  42491. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42492. get: function () {
  42493. return StandardMaterial._RefractionTextureEnabled;
  42494. },
  42495. set: function (value) {
  42496. if (StandardMaterial._RefractionTextureEnabled === value) {
  42497. return;
  42498. }
  42499. StandardMaterial._RefractionTextureEnabled = value;
  42500. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42501. },
  42502. enumerable: true,
  42503. configurable: true
  42504. });
  42505. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42506. get: function () {
  42507. return StandardMaterial._ColorGradingTextureEnabled;
  42508. },
  42509. set: function (value) {
  42510. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42511. return;
  42512. }
  42513. StandardMaterial._ColorGradingTextureEnabled = value;
  42514. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42515. },
  42516. enumerable: true,
  42517. configurable: true
  42518. });
  42519. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42520. get: function () {
  42521. return StandardMaterial._FresnelEnabled;
  42522. },
  42523. set: function (value) {
  42524. if (StandardMaterial._FresnelEnabled === value) {
  42525. return;
  42526. }
  42527. StandardMaterial._FresnelEnabled = value;
  42528. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42529. },
  42530. enumerable: true,
  42531. configurable: true
  42532. });
  42533. // Flags used to enable or disable a type of texture for all Standard Materials
  42534. StandardMaterial._DiffuseTextureEnabled = true;
  42535. StandardMaterial._AmbientTextureEnabled = true;
  42536. StandardMaterial._OpacityTextureEnabled = true;
  42537. StandardMaterial._ReflectionTextureEnabled = true;
  42538. StandardMaterial._EmissiveTextureEnabled = true;
  42539. StandardMaterial._SpecularTextureEnabled = true;
  42540. StandardMaterial._BumpTextureEnabled = true;
  42541. StandardMaterial._LightmapTextureEnabled = true;
  42542. StandardMaterial._RefractionTextureEnabled = true;
  42543. StandardMaterial._ColorGradingTextureEnabled = true;
  42544. StandardMaterial._FresnelEnabled = true;
  42545. __decorate([
  42546. BABYLON.serializeAsTexture("diffuseTexture")
  42547. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42548. __decorate([
  42549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42550. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42551. __decorate([
  42552. BABYLON.serializeAsTexture("ambientTexture")
  42553. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42554. __decorate([
  42555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42556. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42557. __decorate([
  42558. BABYLON.serializeAsTexture("opacityTexture")
  42559. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42560. __decorate([
  42561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42562. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42563. __decorate([
  42564. BABYLON.serializeAsTexture("reflectionTexture")
  42565. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42566. __decorate([
  42567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42568. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42569. __decorate([
  42570. BABYLON.serializeAsTexture("emissiveTexture")
  42571. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42572. __decorate([
  42573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42574. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42575. __decorate([
  42576. BABYLON.serializeAsTexture("specularTexture")
  42577. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42578. __decorate([
  42579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42580. ], StandardMaterial.prototype, "specularTexture", void 0);
  42581. __decorate([
  42582. BABYLON.serializeAsTexture("bumpTexture")
  42583. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42584. __decorate([
  42585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42586. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42587. __decorate([
  42588. BABYLON.serializeAsTexture("lightmapTexture")
  42589. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42590. __decorate([
  42591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42592. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42593. __decorate([
  42594. BABYLON.serializeAsTexture("refractionTexture")
  42595. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42596. __decorate([
  42597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42598. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42599. __decorate([
  42600. BABYLON.serializeAsColor3("ambient")
  42601. ], StandardMaterial.prototype, "ambientColor", void 0);
  42602. __decorate([
  42603. BABYLON.serializeAsColor3("diffuse")
  42604. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42605. __decorate([
  42606. BABYLON.serializeAsColor3("specular")
  42607. ], StandardMaterial.prototype, "specularColor", void 0);
  42608. __decorate([
  42609. BABYLON.serializeAsColor3("emissive")
  42610. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42611. __decorate([
  42612. BABYLON.serialize()
  42613. ], StandardMaterial.prototype, "specularPower", void 0);
  42614. __decorate([
  42615. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42616. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42617. __decorate([
  42618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42619. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42620. __decorate([
  42621. BABYLON.serialize("useEmissiveAsIllumination")
  42622. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42623. __decorate([
  42624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42625. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42626. __decorate([
  42627. BABYLON.serialize("linkEmissiveWithDiffuse")
  42628. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42629. __decorate([
  42630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42631. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42632. __decorate([
  42633. BABYLON.serialize("useSpecularOverAlpha")
  42634. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42635. __decorate([
  42636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42637. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42638. __decorate([
  42639. BABYLON.serialize("useReflectionOverAlpha")
  42640. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42641. __decorate([
  42642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42643. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42644. __decorate([
  42645. BABYLON.serialize("disableLighting")
  42646. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42647. __decorate([
  42648. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42649. ], StandardMaterial.prototype, "disableLighting", void 0);
  42650. __decorate([
  42651. BABYLON.serialize("useObjectSpaceNormalMap")
  42652. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42653. __decorate([
  42654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42655. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42656. __decorate([
  42657. BABYLON.serialize("useParallax")
  42658. ], StandardMaterial.prototype, "_useParallax", void 0);
  42659. __decorate([
  42660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42661. ], StandardMaterial.prototype, "useParallax", void 0);
  42662. __decorate([
  42663. BABYLON.serialize("useParallaxOcclusion")
  42664. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42665. __decorate([
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42667. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42668. __decorate([
  42669. BABYLON.serialize()
  42670. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42671. __decorate([
  42672. BABYLON.serialize("roughness")
  42673. ], StandardMaterial.prototype, "_roughness", void 0);
  42674. __decorate([
  42675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42676. ], StandardMaterial.prototype, "roughness", void 0);
  42677. __decorate([
  42678. BABYLON.serialize()
  42679. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42680. __decorate([
  42681. BABYLON.serialize()
  42682. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42683. __decorate([
  42684. BABYLON.serialize()
  42685. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42686. __decorate([
  42687. BABYLON.serialize("useLightmapAsShadowmap")
  42688. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42689. __decorate([
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42691. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42692. __decorate([
  42693. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42694. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42695. __decorate([
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42697. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42698. __decorate([
  42699. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42700. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42701. __decorate([
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42703. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42704. __decorate([
  42705. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42706. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42707. __decorate([
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42709. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42710. __decorate([
  42711. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42712. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42713. __decorate([
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42715. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42716. __decorate([
  42717. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42718. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42719. __decorate([
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42721. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42722. __decorate([
  42723. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42724. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42725. __decorate([
  42726. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42727. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42728. __decorate([
  42729. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42730. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42731. __decorate([
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42734. __decorate([
  42735. BABYLON.serialize("maxSimultaneousLights")
  42736. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42737. __decorate([
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42739. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42740. __decorate([
  42741. BABYLON.serialize("invertNormalMapX")
  42742. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42743. __decorate([
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42745. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42746. __decorate([
  42747. BABYLON.serialize("invertNormalMapY")
  42748. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42749. __decorate([
  42750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42751. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42752. __decorate([
  42753. BABYLON.serialize("twoSidedLighting")
  42754. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42755. __decorate([
  42756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42757. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42758. __decorate([
  42759. BABYLON.serialize()
  42760. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42761. return StandardMaterial;
  42762. }(BABYLON.PushMaterial));
  42763. BABYLON.StandardMaterial = StandardMaterial;
  42764. })(BABYLON || (BABYLON = {}));
  42765. //# sourceMappingURL=babylon.standardMaterial.js.map
  42766. var BABYLON;
  42767. (function (BABYLON) {
  42768. /**
  42769. * Manages the defines for the PBR Material.
  42770. * @hiddenChildren
  42771. */
  42772. var PBRMaterialDefines = /** @class */ (function (_super) {
  42773. __extends(PBRMaterialDefines, _super);
  42774. /**
  42775. * Initializes the PBR Material defines.
  42776. */
  42777. function PBRMaterialDefines() {
  42778. var _this = _super.call(this) || this;
  42779. _this.PBR = true;
  42780. _this.MAINUV1 = false;
  42781. _this.MAINUV2 = false;
  42782. _this.UV1 = false;
  42783. _this.UV2 = false;
  42784. _this.ALBEDO = false;
  42785. _this.ALBEDODIRECTUV = 0;
  42786. _this.VERTEXCOLOR = false;
  42787. _this.AMBIENT = false;
  42788. _this.AMBIENTDIRECTUV = 0;
  42789. _this.AMBIENTINGRAYSCALE = false;
  42790. _this.OPACITY = false;
  42791. _this.VERTEXALPHA = false;
  42792. _this.OPACITYDIRECTUV = 0;
  42793. _this.OPACITYRGB = false;
  42794. _this.ALPHATEST = false;
  42795. _this.DEPTHPREPASS = false;
  42796. _this.ALPHABLEND = false;
  42797. _this.ALPHAFROMALBEDO = false;
  42798. _this.ALPHATESTVALUE = "0.5";
  42799. _this.SPECULAROVERALPHA = false;
  42800. _this.RADIANCEOVERALPHA = false;
  42801. _this.ALPHAFRESNEL = false;
  42802. _this.LINEARALPHAFRESNEL = false;
  42803. _this.PREMULTIPLYALPHA = false;
  42804. _this.EMISSIVE = false;
  42805. _this.EMISSIVEDIRECTUV = 0;
  42806. _this.REFLECTIVITY = false;
  42807. _this.REFLECTIVITYDIRECTUV = 0;
  42808. _this.SPECULARTERM = false;
  42809. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  42810. _this.MICROSURFACEAUTOMATIC = false;
  42811. _this.LODBASEDMICROSFURACE = false;
  42812. _this.MICROSURFACEMAP = false;
  42813. _this.MICROSURFACEMAPDIRECTUV = 0;
  42814. _this.METALLICWORKFLOW = false;
  42815. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  42816. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  42817. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  42818. _this.AOSTOREINMETALMAPRED = false;
  42819. _this.ENVIRONMENTBRDF = false;
  42820. _this.NORMAL = false;
  42821. _this.TANGENT = false;
  42822. _this.BUMP = false;
  42823. _this.BUMPDIRECTUV = 0;
  42824. _this.OBJECTSPACE_NORMALMAP = false;
  42825. _this.PARALLAX = false;
  42826. _this.PARALLAXOCCLUSION = false;
  42827. _this.NORMALXYSCALE = true;
  42828. _this.LIGHTMAP = false;
  42829. _this.LIGHTMAPDIRECTUV = 0;
  42830. _this.USELIGHTMAPASSHADOWMAP = false;
  42831. _this.GAMMALIGHTMAP = false;
  42832. _this.REFLECTION = false;
  42833. _this.REFLECTIONMAP_3D = false;
  42834. _this.REFLECTIONMAP_SPHERICAL = false;
  42835. _this.REFLECTIONMAP_PLANAR = false;
  42836. _this.REFLECTIONMAP_CUBIC = false;
  42837. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42838. _this.REFLECTIONMAP_PROJECTION = false;
  42839. _this.REFLECTIONMAP_SKYBOX = false;
  42840. _this.REFLECTIONMAP_EXPLICIT = false;
  42841. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42842. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42843. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42844. _this.INVERTCUBICMAP = false;
  42845. _this.USESPHERICALFROMREFLECTIONMAP = false;
  42846. _this.USESPHERICALINVERTEX = false;
  42847. _this.REFLECTIONMAP_OPPOSITEZ = false;
  42848. _this.LODINREFLECTIONALPHA = false;
  42849. _this.GAMMAREFLECTION = false;
  42850. _this.RGBDREFLECTION = false;
  42851. _this.RADIANCEOCCLUSION = false;
  42852. _this.HORIZONOCCLUSION = false;
  42853. _this.REFRACTION = false;
  42854. _this.REFRACTIONMAP_3D = false;
  42855. _this.REFRACTIONMAP_OPPOSITEZ = false;
  42856. _this.LODINREFRACTIONALPHA = false;
  42857. _this.GAMMAREFRACTION = false;
  42858. _this.RGBDREFRACTION = false;
  42859. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  42860. _this.INSTANCES = false;
  42861. _this.NUM_BONE_INFLUENCERS = 0;
  42862. _this.BonesPerMesh = 0;
  42863. _this.NONUNIFORMSCALING = false;
  42864. _this.MORPHTARGETS = false;
  42865. _this.MORPHTARGETS_NORMAL = false;
  42866. _this.MORPHTARGETS_TANGENT = false;
  42867. _this.NUM_MORPH_INFLUENCERS = 0;
  42868. _this.IMAGEPROCESSING = false;
  42869. _this.VIGNETTE = false;
  42870. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42871. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42872. _this.TONEMAPPING = false;
  42873. _this.CONTRAST = false;
  42874. _this.COLORCURVES = false;
  42875. _this.COLORGRADING = false;
  42876. _this.COLORGRADING3D = false;
  42877. _this.SAMPLER3DGREENDEPTH = false;
  42878. _this.SAMPLER3DBGRMAP = false;
  42879. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42880. _this.EXPOSURE = false;
  42881. _this.USEPHYSICALLIGHTFALLOFF = false;
  42882. _this.TWOSIDEDLIGHTING = false;
  42883. _this.SHADOWFLOAT = false;
  42884. _this.CLIPPLANE = false;
  42885. _this.POINTSIZE = false;
  42886. _this.FOG = false;
  42887. _this.LOGARITHMICDEPTH = false;
  42888. _this.FORCENORMALFORWARD = false;
  42889. _this.SPECULARAA = false;
  42890. _this.UNLIT = false;
  42891. _this.rebuild();
  42892. return _this;
  42893. }
  42894. /**
  42895. * Resets the PBR Material defines.
  42896. */
  42897. PBRMaterialDefines.prototype.reset = function () {
  42898. _super.prototype.reset.call(this);
  42899. this.ALPHATESTVALUE = "0.5";
  42900. this.PBR = true;
  42901. };
  42902. return PBRMaterialDefines;
  42903. }(BABYLON.MaterialDefines));
  42904. /**
  42905. * The Physically based material base class of BJS.
  42906. *
  42907. * This offers the main features of a standard PBR material.
  42908. * For more information, please refer to the documentation :
  42909. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42910. */
  42911. var PBRBaseMaterial = /** @class */ (function (_super) {
  42912. __extends(PBRBaseMaterial, _super);
  42913. /**
  42914. * Instantiates a new PBRMaterial instance.
  42915. *
  42916. * @param name The material name
  42917. * @param scene The scene the material will be use in.
  42918. */
  42919. function PBRBaseMaterial(name, scene) {
  42920. var _this = _super.call(this, name, scene) || this;
  42921. /**
  42922. * Intensity of the direct lights e.g. the four lights available in your scene.
  42923. * This impacts both the direct diffuse and specular highlights.
  42924. */
  42925. _this._directIntensity = 1.0;
  42926. /**
  42927. * Intensity of the emissive part of the material.
  42928. * This helps controlling the emissive effect without modifying the emissive color.
  42929. */
  42930. _this._emissiveIntensity = 1.0;
  42931. /**
  42932. * Intensity of the environment e.g. how much the environment will light the object
  42933. * either through harmonics for rough material or through the refelction for shiny ones.
  42934. */
  42935. _this._environmentIntensity = 1.0;
  42936. /**
  42937. * This is a special control allowing the reduction of the specular highlights coming from the
  42938. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42939. */
  42940. _this._specularIntensity = 1.0;
  42941. /**
  42942. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  42943. */
  42944. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  42945. /**
  42946. * Debug Control allowing disabling the bump map on this material.
  42947. */
  42948. _this._disableBumpMap = false;
  42949. /**
  42950. * AKA Occlusion Texture Intensity in other nomenclature.
  42951. */
  42952. _this._ambientTextureStrength = 1.0;
  42953. /**
  42954. * The color of a material in ambient lighting.
  42955. */
  42956. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  42957. /**
  42958. * AKA Diffuse Color in other nomenclature.
  42959. */
  42960. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  42961. /**
  42962. * AKA Specular Color in other nomenclature.
  42963. */
  42964. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42965. /**
  42966. * The color applied when light is reflected from a material.
  42967. */
  42968. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  42969. /**
  42970. * The color applied when light is emitted from a material.
  42971. */
  42972. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  42973. /**
  42974. * AKA Glossiness in other nomenclature.
  42975. */
  42976. _this._microSurface = 0.9;
  42977. /**
  42978. * source material index of refraction (IOR)' / 'destination material IOR.
  42979. */
  42980. _this._indexOfRefraction = 0.66;
  42981. /**
  42982. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42983. */
  42984. _this._invertRefractionY = false;
  42985. /**
  42986. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42987. * Materials half opaque for instance using refraction could benefit from this control.
  42988. */
  42989. _this._linkRefractionWithTransparency = false;
  42990. /**
  42991. * Specifies that the material will use the light map as a show map.
  42992. */
  42993. _this._useLightmapAsShadowmap = false;
  42994. /**
  42995. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42996. * makes the reflect vector face the model (under horizon).
  42997. */
  42998. _this._useHorizonOcclusion = true;
  42999. /**
  43000. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43001. * too much the area relying on ambient texture to define their ambient occlusion.
  43002. */
  43003. _this._useRadianceOcclusion = true;
  43004. /**
  43005. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43006. */
  43007. _this._useAlphaFromAlbedoTexture = false;
  43008. /**
  43009. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43010. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43011. */
  43012. _this._useSpecularOverAlpha = true;
  43013. /**
  43014. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43015. */
  43016. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43017. /**
  43018. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43019. */
  43020. _this._useRoughnessFromMetallicTextureAlpha = true;
  43021. /**
  43022. * Specifies if the metallic texture contains the roughness information in its green channel.
  43023. */
  43024. _this._useRoughnessFromMetallicTextureGreen = false;
  43025. /**
  43026. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43027. */
  43028. _this._useMetallnessFromMetallicTextureBlue = false;
  43029. /**
  43030. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43031. */
  43032. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43033. /**
  43034. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43035. */
  43036. _this._useAmbientInGrayScale = false;
  43037. /**
  43038. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43039. * The material will try to infer what glossiness each pixel should be.
  43040. */
  43041. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43042. /**
  43043. * BJS is using an harcoded light falloff based on a manually sets up range.
  43044. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43045. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43046. */
  43047. _this._usePhysicalLightFalloff = true;
  43048. /**
  43049. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43050. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43051. */
  43052. _this._useRadianceOverAlpha = true;
  43053. /**
  43054. * Allows using an object space normal map (instead of tangent space).
  43055. */
  43056. _this._useObjectSpaceNormalMap = false;
  43057. /**
  43058. * Allows using the bump map in parallax mode.
  43059. */
  43060. _this._useParallax = false;
  43061. /**
  43062. * Allows using the bump map in parallax occlusion mode.
  43063. */
  43064. _this._useParallaxOcclusion = false;
  43065. /**
  43066. * Controls the scale bias of the parallax mode.
  43067. */
  43068. _this._parallaxScaleBias = 0.05;
  43069. /**
  43070. * If sets to true, disables all the lights affecting the material.
  43071. */
  43072. _this._disableLighting = false;
  43073. /**
  43074. * Number of Simultaneous lights allowed on the material.
  43075. */
  43076. _this._maxSimultaneousLights = 4;
  43077. /**
  43078. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43079. */
  43080. _this._invertNormalMapX = false;
  43081. /**
  43082. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43083. */
  43084. _this._invertNormalMapY = false;
  43085. /**
  43086. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43087. */
  43088. _this._twoSidedLighting = false;
  43089. /**
  43090. * Defines the alpha limits in alpha test mode.
  43091. */
  43092. _this._alphaCutOff = 0.4;
  43093. /**
  43094. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43095. */
  43096. _this._forceAlphaTest = false;
  43097. /**
  43098. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43099. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43100. */
  43101. _this._useAlphaFresnel = false;
  43102. /**
  43103. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43104. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43105. */
  43106. _this._useLinearAlphaFresnel = false;
  43107. /**
  43108. * The transparency mode of the material.
  43109. */
  43110. _this._transparencyMode = null;
  43111. /**
  43112. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43113. * from cos thetav and roughness:
  43114. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43115. */
  43116. _this._environmentBRDFTexture = null;
  43117. /**
  43118. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43119. */
  43120. _this._forceIrradianceInFragment = false;
  43121. /**
  43122. * Force normal to face away from face.
  43123. */
  43124. _this._forceNormalForward = false;
  43125. /**
  43126. * Enables specular anti aliasing in the PBR shader.
  43127. * It will both interacts on the Geometry for analytical and IBL lighting.
  43128. * It also prefilter the roughness map based on the bump values.
  43129. */
  43130. _this._enableSpecularAntiAliasing = false;
  43131. /**
  43132. * Stores the available render targets.
  43133. */
  43134. _this._renderTargets = new BABYLON.SmartArray(16);
  43135. /**
  43136. * Sets the global ambient color for the material used in lighting calculations.
  43137. */
  43138. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43139. /**
  43140. * If set to true, no lighting calculations will be applied.
  43141. */
  43142. _this._unlit = false;
  43143. // Setup the default processing configuration to the scene.
  43144. _this._attachImageProcessingConfiguration(null);
  43145. _this.getRenderTargetTextures = function () {
  43146. _this._renderTargets.reset();
  43147. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43148. _this._renderTargets.push(_this._reflectionTexture);
  43149. }
  43150. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43151. _this._renderTargets.push(_this._refractionTexture);
  43152. }
  43153. return _this._renderTargets;
  43154. };
  43155. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43156. return _this;
  43157. }
  43158. /**
  43159. * Attaches a new image processing configuration to the PBR Material.
  43160. * @param configuration
  43161. */
  43162. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43163. var _this = this;
  43164. if (configuration === this._imageProcessingConfiguration) {
  43165. return;
  43166. }
  43167. // Detaches observer.
  43168. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43169. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43170. }
  43171. // Pick the scene configuration if needed.
  43172. if (!configuration) {
  43173. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43174. }
  43175. else {
  43176. this._imageProcessingConfiguration = configuration;
  43177. }
  43178. // Attaches observer.
  43179. if (this._imageProcessingConfiguration) {
  43180. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43181. _this._markAllSubMeshesAsImageProcessingDirty();
  43182. });
  43183. }
  43184. };
  43185. /**
  43186. * Gets the name of the material class.
  43187. */
  43188. PBRBaseMaterial.prototype.getClassName = function () {
  43189. return "PBRBaseMaterial";
  43190. };
  43191. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43192. /**
  43193. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43194. */
  43195. get: function () {
  43196. return this._useLogarithmicDepth;
  43197. },
  43198. /**
  43199. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43200. */
  43201. set: function (value) {
  43202. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43203. },
  43204. enumerable: true,
  43205. configurable: true
  43206. });
  43207. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43208. /**
  43209. * Gets the current transparency mode.
  43210. */
  43211. get: function () {
  43212. return this._transparencyMode;
  43213. },
  43214. /**
  43215. * Sets the transparency mode of the material.
  43216. *
  43217. * | Value | Type | Description |
  43218. * | ----- | ----------------------------------- | ----------- |
  43219. * | 0 | OPAQUE | |
  43220. * | 1 | ALPHATEST | |
  43221. * | 2 | ALPHABLEND | |
  43222. * | 3 | ALPHATESTANDBLEND | |
  43223. *
  43224. */
  43225. set: function (value) {
  43226. if (this._transparencyMode === value) {
  43227. return;
  43228. }
  43229. this._transparencyMode = value;
  43230. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43231. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43232. },
  43233. enumerable: true,
  43234. configurable: true
  43235. });
  43236. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43237. /**
  43238. * Returns true if alpha blending should be disabled.
  43239. */
  43240. get: function () {
  43241. return (this._linkRefractionWithTransparency ||
  43242. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43243. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43244. },
  43245. enumerable: true,
  43246. configurable: true
  43247. });
  43248. /**
  43249. * Specifies whether or not this material should be rendered in alpha blend mode.
  43250. */
  43251. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43252. if (this._disableAlphaBlending) {
  43253. return false;
  43254. }
  43255. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43256. };
  43257. /**
  43258. * Specifies if the mesh will require alpha blending.
  43259. * @param mesh - BJS mesh.
  43260. */
  43261. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43262. if (this._disableAlphaBlending) {
  43263. return false;
  43264. }
  43265. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43266. };
  43267. /**
  43268. * Specifies whether or not this material should be rendered in alpha test mode.
  43269. */
  43270. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43271. if (this._forceAlphaTest) {
  43272. return true;
  43273. }
  43274. if (this._linkRefractionWithTransparency) {
  43275. return false;
  43276. }
  43277. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43278. };
  43279. /**
  43280. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43281. */
  43282. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43283. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43284. };
  43285. /**
  43286. * Gets the texture used for the alpha test.
  43287. */
  43288. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43289. return this._albedoTexture;
  43290. };
  43291. /**
  43292. * Specifies that the submesh is ready to be used.
  43293. * @param mesh - BJS mesh.
  43294. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43295. * @param useInstances - Specifies that instances should be used.
  43296. * @returns - boolean indicating that the submesh is ready or not.
  43297. */
  43298. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43299. if (subMesh.effect && this.isFrozen) {
  43300. if (this._wasPreviouslyReady) {
  43301. return true;
  43302. }
  43303. }
  43304. if (!subMesh._materialDefines) {
  43305. subMesh._materialDefines = new PBRMaterialDefines();
  43306. }
  43307. var defines = subMesh._materialDefines;
  43308. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43309. if (defines._renderId === this.getScene().getRenderId()) {
  43310. return true;
  43311. }
  43312. }
  43313. var scene = this.getScene();
  43314. var engine = scene.getEngine();
  43315. if (defines._areTexturesDirty) {
  43316. if (scene.texturesEnabled) {
  43317. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43318. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43319. return false;
  43320. }
  43321. }
  43322. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43323. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43324. return false;
  43325. }
  43326. }
  43327. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43328. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43329. return false;
  43330. }
  43331. }
  43332. var reflectionTexture = this._getReflectionTexture();
  43333. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43334. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43335. return false;
  43336. }
  43337. }
  43338. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43339. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43340. return false;
  43341. }
  43342. }
  43343. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43344. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43345. return false;
  43346. }
  43347. }
  43348. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43349. if (this._metallicTexture) {
  43350. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43351. return false;
  43352. }
  43353. }
  43354. else if (this._reflectivityTexture) {
  43355. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43356. return false;
  43357. }
  43358. }
  43359. if (this._microSurfaceTexture) {
  43360. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43361. return false;
  43362. }
  43363. }
  43364. }
  43365. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43366. // Bump texture cannot be not blocking.
  43367. if (!this._bumpTexture.isReady()) {
  43368. return false;
  43369. }
  43370. }
  43371. var refractionTexture = this._getRefractionTexture();
  43372. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43373. if (!refractionTexture.isReadyOrNotBlocking()) {
  43374. return false;
  43375. }
  43376. }
  43377. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43378. // This is blocking.
  43379. if (!this._environmentBRDFTexture.isReady()) {
  43380. return false;
  43381. }
  43382. }
  43383. }
  43384. }
  43385. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43386. if (!this._imageProcessingConfiguration.isReady()) {
  43387. return false;
  43388. }
  43389. }
  43390. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43391. mesh.createNormals(true);
  43392. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43393. }
  43394. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43395. if (effect) {
  43396. scene.resetCachedMaterial();
  43397. subMesh.setEffect(effect, defines);
  43398. this.buildUniformLayout();
  43399. }
  43400. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43401. return false;
  43402. }
  43403. defines._renderId = scene.getRenderId();
  43404. this._wasPreviouslyReady = true;
  43405. return true;
  43406. };
  43407. /**
  43408. * Specifies if the material uses metallic roughness workflow.
  43409. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43410. */
  43411. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43412. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43413. return true;
  43414. }
  43415. return false;
  43416. };
  43417. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43418. if (onCompiled === void 0) { onCompiled = null; }
  43419. if (onError === void 0) { onError = null; }
  43420. if (useInstances === void 0) { useInstances = null; }
  43421. if (useClipPlane === void 0) { useClipPlane = null; }
  43422. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43423. if (!defines.isDirty) {
  43424. return null;
  43425. }
  43426. defines.markAsProcessed();
  43427. var scene = this.getScene();
  43428. var engine = scene.getEngine();
  43429. // Fallbacks
  43430. var fallbacks = new BABYLON.EffectFallbacks();
  43431. var fallbackRank = 0;
  43432. if (defines.USESPHERICALINVERTEX) {
  43433. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43434. }
  43435. if (defines.FOG) {
  43436. fallbacks.addFallback(fallbackRank, "FOG");
  43437. }
  43438. if (defines.SPECULARAA) {
  43439. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43440. }
  43441. if (defines.POINTSIZE) {
  43442. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43443. }
  43444. if (defines.LOGARITHMICDEPTH) {
  43445. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43446. }
  43447. if (defines.PARALLAX) {
  43448. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43449. }
  43450. if (defines.PARALLAXOCCLUSION) {
  43451. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43452. }
  43453. if (defines.ENVIRONMENTBRDF) {
  43454. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43455. }
  43456. if (defines.TANGENT) {
  43457. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43458. }
  43459. if (defines.BUMP) {
  43460. fallbacks.addFallback(fallbackRank++, "BUMP");
  43461. }
  43462. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43463. if (defines.SPECULARTERM) {
  43464. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43465. }
  43466. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43467. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43468. }
  43469. if (defines.LIGHTMAP) {
  43470. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43471. }
  43472. if (defines.NORMAL) {
  43473. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43474. }
  43475. if (defines.AMBIENT) {
  43476. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43477. }
  43478. if (defines.EMISSIVE) {
  43479. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43480. }
  43481. if (defines.VERTEXCOLOR) {
  43482. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43483. }
  43484. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43485. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43486. }
  43487. if (defines.MORPHTARGETS) {
  43488. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43489. }
  43490. //Attributes
  43491. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43492. if (defines.NORMAL) {
  43493. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43494. }
  43495. if (defines.TANGENT) {
  43496. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43497. }
  43498. if (defines.UV1) {
  43499. attribs.push(BABYLON.VertexBuffer.UVKind);
  43500. }
  43501. if (defines.UV2) {
  43502. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43503. }
  43504. if (defines.VERTEXCOLOR) {
  43505. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43506. }
  43507. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43508. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43509. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43510. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43511. "vFogInfos", "vFogColor", "pointSize",
  43512. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43513. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43514. "mBones",
  43515. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43516. "vLightingIntensity",
  43517. "logarithmicDepthConstant",
  43518. "vSphericalX", "vSphericalY", "vSphericalZ",
  43519. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43520. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43521. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43522. "vTangentSpaceParams"
  43523. ];
  43524. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43525. "bumpSampler", "lightmapSampler", "opacitySampler",
  43526. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43527. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43528. "microSurfaceSampler", "environmentBrdfSampler"];
  43529. var uniformBuffers = ["Material", "Scene"];
  43530. if (BABYLON.ImageProcessingConfiguration) {
  43531. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43532. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43533. }
  43534. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43535. uniformsNames: uniforms,
  43536. uniformBuffersNames: uniformBuffers,
  43537. samplers: samplers,
  43538. defines: defines,
  43539. maxSimultaneousLights: this._maxSimultaneousLights
  43540. });
  43541. var join = defines.toString();
  43542. return engine.createEffect("pbr", {
  43543. attributes: attribs,
  43544. uniformsNames: uniforms,
  43545. uniformBuffersNames: uniformBuffers,
  43546. samplers: samplers,
  43547. defines: join,
  43548. fallbacks: fallbacks,
  43549. onCompiled: onCompiled,
  43550. onError: onError,
  43551. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43552. }, engine);
  43553. };
  43554. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43555. if (useInstances === void 0) { useInstances = null; }
  43556. if (useClipPlane === void 0) { useClipPlane = null; }
  43557. var scene = this.getScene();
  43558. var engine = scene.getEngine();
  43559. // Lights
  43560. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43561. defines._needNormals = true;
  43562. // Textures
  43563. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43564. if (defines._areTexturesDirty) {
  43565. defines._needUVs = false;
  43566. if (scene.texturesEnabled) {
  43567. if (scene.getEngine().getCaps().textureLOD) {
  43568. defines.LODBASEDMICROSFURACE = true;
  43569. }
  43570. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43572. }
  43573. else {
  43574. defines.ALBEDO = false;
  43575. }
  43576. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43577. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43578. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43579. }
  43580. else {
  43581. defines.AMBIENT = false;
  43582. }
  43583. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43584. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43585. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43586. }
  43587. else {
  43588. defines.OPACITY = false;
  43589. }
  43590. var reflectionTexture = this._getReflectionTexture();
  43591. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43592. defines.REFLECTION = true;
  43593. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43594. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43595. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43596. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43597. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43598. defines.INVERTCUBICMAP = true;
  43599. }
  43600. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43601. switch (reflectionTexture.coordinatesMode) {
  43602. case BABYLON.Texture.EXPLICIT_MODE:
  43603. defines.REFLECTIONMAP_EXPLICIT = true;
  43604. break;
  43605. case BABYLON.Texture.PLANAR_MODE:
  43606. defines.REFLECTIONMAP_PLANAR = true;
  43607. break;
  43608. case BABYLON.Texture.PROJECTION_MODE:
  43609. defines.REFLECTIONMAP_PROJECTION = true;
  43610. break;
  43611. case BABYLON.Texture.SKYBOX_MODE:
  43612. defines.REFLECTIONMAP_SKYBOX = true;
  43613. break;
  43614. case BABYLON.Texture.SPHERICAL_MODE:
  43615. defines.REFLECTIONMAP_SPHERICAL = true;
  43616. break;
  43617. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43618. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43619. break;
  43620. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43621. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43622. break;
  43623. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43624. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43625. break;
  43626. case BABYLON.Texture.CUBIC_MODE:
  43627. case BABYLON.Texture.INVCUBIC_MODE:
  43628. default:
  43629. defines.REFLECTIONMAP_CUBIC = true;
  43630. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43631. break;
  43632. }
  43633. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43634. if (reflectionTexture.sphericalPolynomial) {
  43635. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43636. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43637. defines.USESPHERICALINVERTEX = false;
  43638. }
  43639. else {
  43640. defines.USESPHERICALINVERTEX = true;
  43641. }
  43642. }
  43643. }
  43644. }
  43645. else {
  43646. defines.REFLECTION = false;
  43647. defines.REFLECTIONMAP_3D = false;
  43648. defines.REFLECTIONMAP_SPHERICAL = false;
  43649. defines.REFLECTIONMAP_PLANAR = false;
  43650. defines.REFLECTIONMAP_CUBIC = false;
  43651. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43652. defines.REFLECTIONMAP_PROJECTION = false;
  43653. defines.REFLECTIONMAP_SKYBOX = false;
  43654. defines.REFLECTIONMAP_EXPLICIT = false;
  43655. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43656. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43657. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43658. defines.INVERTCUBICMAP = false;
  43659. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43660. defines.USESPHERICALINVERTEX = false;
  43661. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43662. defines.LODINREFLECTIONALPHA = false;
  43663. defines.GAMMAREFLECTION = false;
  43664. defines.RGBDREFLECTION = false;
  43665. }
  43666. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43667. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43668. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43669. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43670. }
  43671. else {
  43672. defines.LIGHTMAP = false;
  43673. }
  43674. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43675. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43676. }
  43677. else {
  43678. defines.EMISSIVE = false;
  43679. }
  43680. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43681. if (this._metallicTexture) {
  43682. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43683. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43684. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43685. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43686. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43687. }
  43688. else if (this._reflectivityTexture) {
  43689. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43690. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43691. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43692. }
  43693. else {
  43694. defines.REFLECTIVITY = false;
  43695. }
  43696. if (this._microSurfaceTexture) {
  43697. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43698. }
  43699. else {
  43700. defines.MICROSURFACEMAP = false;
  43701. }
  43702. }
  43703. else {
  43704. defines.REFLECTIVITY = false;
  43705. defines.MICROSURFACEMAP = false;
  43706. }
  43707. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43708. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43709. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43710. defines.PARALLAX = true;
  43711. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43712. }
  43713. else {
  43714. defines.PARALLAX = false;
  43715. }
  43716. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43717. }
  43718. else {
  43719. defines.BUMP = false;
  43720. }
  43721. var refractionTexture = this._getRefractionTexture();
  43722. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43723. defines.REFRACTION = true;
  43724. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  43725. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  43726. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  43727. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  43728. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  43729. if (this._linkRefractionWithTransparency) {
  43730. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  43731. }
  43732. }
  43733. else {
  43734. defines.REFRACTION = false;
  43735. }
  43736. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43737. defines.ENVIRONMENTBRDF = true;
  43738. }
  43739. else {
  43740. defines.ENVIRONMENTBRDF = false;
  43741. }
  43742. if (this._shouldUseAlphaFromAlbedoTexture()) {
  43743. defines.ALPHAFROMALBEDO = true;
  43744. }
  43745. else {
  43746. defines.ALPHAFROMALBEDO = false;
  43747. }
  43748. }
  43749. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43750. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  43751. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  43752. if (!this.backFaceCulling && this._twoSidedLighting) {
  43753. defines.TWOSIDEDLIGHTING = true;
  43754. }
  43755. else {
  43756. defines.TWOSIDEDLIGHTING = false;
  43757. }
  43758. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  43759. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43760. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  43761. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  43762. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  43763. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  43764. }
  43765. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43766. this._imageProcessingConfiguration.prepareDefines(defines);
  43767. }
  43768. defines.FORCENORMALFORWARD = this._forceNormalForward;
  43769. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  43770. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  43771. // Misc.
  43772. if (defines._areMiscDirty) {
  43773. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  43774. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43775. }
  43776. // Values that need to be evaluated on every frame
  43777. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  43778. // Attribs
  43779. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  43780. };
  43781. /**
  43782. * Force shader compilation
  43783. */
  43784. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  43785. var _this = this;
  43786. var localOptions = __assign({ clipPlane: false }, options);
  43787. var defines = new PBRMaterialDefines();
  43788. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  43789. if (effect.isReady()) {
  43790. if (onCompiled) {
  43791. onCompiled(this);
  43792. }
  43793. }
  43794. else {
  43795. effect.onCompileObservable.add(function () {
  43796. if (onCompiled) {
  43797. onCompiled(_this);
  43798. }
  43799. });
  43800. }
  43801. };
  43802. /**
  43803. * Initializes the uniform buffer layout for the shader.
  43804. */
  43805. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  43806. // Order is important !
  43807. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  43808. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  43809. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43810. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43811. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43812. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  43813. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  43814. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43815. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43816. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43817. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43818. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43819. this._uniformBuffer.addUniform("albedoMatrix", 16);
  43820. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43821. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43822. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43823. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43824. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  43825. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  43826. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43827. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43828. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43829. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43830. this._uniformBuffer.addUniform("vReflectionColor", 3);
  43831. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  43832. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  43833. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  43834. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  43835. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  43836. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43837. this._uniformBuffer.addUniform("pointSize", 1);
  43838. this._uniformBuffer.create();
  43839. };
  43840. /**
  43841. * Unbinds the textures.
  43842. */
  43843. PBRBaseMaterial.prototype.unbind = function () {
  43844. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43845. this._uniformBuffer.setTexture("reflectionSampler", null);
  43846. }
  43847. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43848. this._uniformBuffer.setTexture("refractionSampler", null);
  43849. }
  43850. _super.prototype.unbind.call(this);
  43851. };
  43852. /**
  43853. * Binds the submesh data.
  43854. * @param world - The world matrix.
  43855. * @param mesh - The BJS mesh.
  43856. * @param subMesh - A submesh of the BJS mesh.
  43857. */
  43858. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43859. var scene = this.getScene();
  43860. var defines = subMesh._materialDefines;
  43861. if (!defines) {
  43862. return;
  43863. }
  43864. var effect = subMesh.effect;
  43865. if (!effect) {
  43866. return;
  43867. }
  43868. this._activeEffect = effect;
  43869. // Matrices
  43870. this.bindOnlyWorldMatrix(world);
  43871. // Normal Matrix
  43872. if (defines.OBJECTSPACE_NORMALMAP) {
  43873. world.toNormalMatrix(this._normalMatrix);
  43874. this.bindOnlyNormalMatrix(this._normalMatrix);
  43875. }
  43876. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43877. // Bones
  43878. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  43879. var reflectionTexture = null;
  43880. if (mustRebind) {
  43881. this._uniformBuffer.bindToEffect(effect, "Material");
  43882. this.bindViewProjection(effect);
  43883. reflectionTexture = this._getReflectionTexture();
  43884. var refractionTexture = this._getRefractionTexture();
  43885. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43886. // Texture uniforms
  43887. if (scene.texturesEnabled) {
  43888. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43889. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  43890. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  43891. }
  43892. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43893. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  43894. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43895. }
  43896. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43897. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43898. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43899. }
  43900. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43901. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  43902. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  43903. if (reflectionTexture.boundingBoxSize) {
  43904. var cubeTexture = reflectionTexture;
  43905. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43906. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43907. }
  43908. var polynomials = reflectionTexture.sphericalPolynomial;
  43909. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  43910. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  43911. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  43912. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  43913. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  43914. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  43915. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  43916. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  43917. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  43918. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  43919. }
  43920. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  43921. }
  43922. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43923. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43924. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43925. }
  43926. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43927. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43928. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43929. }
  43930. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43931. if (this._metallicTexture) {
  43932. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  43933. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  43934. }
  43935. else if (this._reflectivityTexture) {
  43936. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  43937. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  43938. }
  43939. if (this._microSurfaceTexture) {
  43940. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  43941. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  43942. }
  43943. }
  43944. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43945. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  43946. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43947. if (scene._mirroredCameraPosition) {
  43948. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43949. }
  43950. else {
  43951. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43952. }
  43953. }
  43954. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43955. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  43956. var depth = 1.0;
  43957. if (!refractionTexture.isCube) {
  43958. if (refractionTexture.depth) {
  43959. depth = refractionTexture.depth;
  43960. }
  43961. }
  43962. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  43963. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  43964. }
  43965. }
  43966. // Point size
  43967. if (this.pointsCloud) {
  43968. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43969. }
  43970. // Colors
  43971. if (defines.METALLICWORKFLOW) {
  43972. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  43973. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  43974. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  43975. }
  43976. else {
  43977. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  43978. }
  43979. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  43980. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  43981. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  43982. // Misc
  43983. this._lightingInfos.x = this._directIntensity;
  43984. this._lightingInfos.y = this._emissiveIntensity;
  43985. this._lightingInfos.z = this._environmentIntensity;
  43986. this._lightingInfos.w = this._specularIntensity;
  43987. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  43988. }
  43989. // Textures
  43990. if (scene.texturesEnabled) {
  43991. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43992. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  43993. }
  43994. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43995. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  43996. }
  43997. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43998. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  43999. }
  44000. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44001. if (defines.LODBASEDMICROSFURACE) {
  44002. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44003. }
  44004. else {
  44005. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44006. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44007. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44008. }
  44009. }
  44010. if (defines.ENVIRONMENTBRDF) {
  44011. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44012. }
  44013. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44014. if (defines.LODBASEDMICROSFURACE) {
  44015. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44016. }
  44017. else {
  44018. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44019. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44020. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44021. }
  44022. }
  44023. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44024. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44025. }
  44026. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44027. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44028. }
  44029. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44030. if (this._metallicTexture) {
  44031. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44032. }
  44033. else if (this._reflectivityTexture) {
  44034. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44035. }
  44036. if (this._microSurfaceTexture) {
  44037. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44038. }
  44039. }
  44040. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44041. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44042. }
  44043. }
  44044. // Clip plane
  44045. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44046. // Colors
  44047. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44048. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44049. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44050. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44051. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44052. }
  44053. if (mustRebind || !this.isFrozen) {
  44054. // Lights
  44055. if (scene.lightsEnabled && !this._disableLighting) {
  44056. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44057. }
  44058. // View
  44059. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44060. this.bindView(effect);
  44061. }
  44062. // Fog
  44063. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44064. // Morph targets
  44065. if (defines.NUM_MORPH_INFLUENCERS) {
  44066. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44067. }
  44068. // image processing
  44069. this._imageProcessingConfiguration.bind(this._activeEffect);
  44070. // Log. depth
  44071. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44072. }
  44073. this._uniformBuffer.update();
  44074. this._afterBind(mesh, this._activeEffect);
  44075. };
  44076. /**
  44077. * Returns the animatable textures.
  44078. * @returns - Array of animatable textures.
  44079. */
  44080. PBRBaseMaterial.prototype.getAnimatables = function () {
  44081. var results = [];
  44082. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44083. results.push(this._albedoTexture);
  44084. }
  44085. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44086. results.push(this._ambientTexture);
  44087. }
  44088. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44089. results.push(this._opacityTexture);
  44090. }
  44091. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44092. results.push(this._reflectionTexture);
  44093. }
  44094. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44095. results.push(this._emissiveTexture);
  44096. }
  44097. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44098. results.push(this._metallicTexture);
  44099. }
  44100. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44101. results.push(this._reflectivityTexture);
  44102. }
  44103. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44104. results.push(this._bumpTexture);
  44105. }
  44106. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44107. results.push(this._lightmapTexture);
  44108. }
  44109. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44110. results.push(this._refractionTexture);
  44111. }
  44112. return results;
  44113. };
  44114. /**
  44115. * Returns the texture used for reflections.
  44116. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44117. */
  44118. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44119. if (this._reflectionTexture) {
  44120. return this._reflectionTexture;
  44121. }
  44122. return this.getScene().environmentTexture;
  44123. };
  44124. /**
  44125. * Returns the texture used for refraction or null if none is used.
  44126. * @returns - Refection texture if present. If no refraction texture and refraction
  44127. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44128. */
  44129. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44130. if (this._refractionTexture) {
  44131. return this._refractionTexture;
  44132. }
  44133. if (this._linkRefractionWithTransparency) {
  44134. return this.getScene().environmentTexture;
  44135. }
  44136. return null;
  44137. };
  44138. /**
  44139. * Disposes the resources of the material.
  44140. * @param forceDisposeEffect - Forces the disposal of effects.
  44141. * @param forceDisposeTextures - Forces the disposal of all textures.
  44142. */
  44143. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44144. if (forceDisposeTextures) {
  44145. if (this._albedoTexture) {
  44146. this._albedoTexture.dispose();
  44147. }
  44148. if (this._ambientTexture) {
  44149. this._ambientTexture.dispose();
  44150. }
  44151. if (this._opacityTexture) {
  44152. this._opacityTexture.dispose();
  44153. }
  44154. if (this._reflectionTexture) {
  44155. this._reflectionTexture.dispose();
  44156. }
  44157. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44158. this._environmentBRDFTexture.dispose();
  44159. }
  44160. if (this._emissiveTexture) {
  44161. this._emissiveTexture.dispose();
  44162. }
  44163. if (this._metallicTexture) {
  44164. this._metallicTexture.dispose();
  44165. }
  44166. if (this._reflectivityTexture) {
  44167. this._reflectivityTexture.dispose();
  44168. }
  44169. if (this._bumpTexture) {
  44170. this._bumpTexture.dispose();
  44171. }
  44172. if (this._lightmapTexture) {
  44173. this._lightmapTexture.dispose();
  44174. }
  44175. if (this._refractionTexture) {
  44176. this._refractionTexture.dispose();
  44177. }
  44178. }
  44179. this._renderTargets.dispose();
  44180. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44181. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44182. }
  44183. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44184. };
  44185. /**
  44186. * Stores the reflectivity values based on metallic roughness workflow.
  44187. */
  44188. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44189. __decorate([
  44190. BABYLON.serializeAsImageProcessingConfiguration()
  44191. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44192. __decorate([
  44193. BABYLON.serialize()
  44194. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44195. __decorate([
  44196. BABYLON.serialize()
  44197. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44198. return PBRBaseMaterial;
  44199. }(BABYLON.PushMaterial));
  44200. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44201. })(BABYLON || (BABYLON = {}));
  44202. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44203. var BABYLON;
  44204. (function (BABYLON) {
  44205. /**
  44206. * The Physically based simple base material of BJS.
  44207. *
  44208. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44209. * It is used as the base class for both the specGloss and metalRough conventions.
  44210. */
  44211. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44212. __extends(PBRBaseSimpleMaterial, _super);
  44213. /**
  44214. * Instantiates a new PBRMaterial instance.
  44215. *
  44216. * @param name The material name
  44217. * @param scene The scene the material will be use in.
  44218. */
  44219. function PBRBaseSimpleMaterial(name, scene) {
  44220. var _this = _super.call(this, name, scene) || this;
  44221. /**
  44222. * Number of Simultaneous lights allowed on the material.
  44223. */
  44224. _this.maxSimultaneousLights = 4;
  44225. /**
  44226. * If sets to true, disables all the lights affecting the material.
  44227. */
  44228. _this.disableLighting = false;
  44229. /**
  44230. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44231. */
  44232. _this.invertNormalMapX = false;
  44233. /**
  44234. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44235. */
  44236. _this.invertNormalMapY = false;
  44237. /**
  44238. * Emissivie color used to self-illuminate the model.
  44239. */
  44240. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44241. /**
  44242. * Occlusion Channel Strenght.
  44243. */
  44244. _this.occlusionStrength = 1.0;
  44245. _this.useLightmapAsShadowmap = false;
  44246. _this._useAlphaFromAlbedoTexture = true;
  44247. _this._useAmbientInGrayScale = true;
  44248. return _this;
  44249. }
  44250. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44251. /**
  44252. * Gets the current double sided mode.
  44253. */
  44254. get: function () {
  44255. return this._twoSidedLighting;
  44256. },
  44257. /**
  44258. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44259. */
  44260. set: function (value) {
  44261. if (this._twoSidedLighting === value) {
  44262. return;
  44263. }
  44264. this._twoSidedLighting = value;
  44265. this.backFaceCulling = !value;
  44266. this._markAllSubMeshesAsTexturesDirty();
  44267. },
  44268. enumerable: true,
  44269. configurable: true
  44270. });
  44271. /**
  44272. * Return the active textures of the material.
  44273. */
  44274. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44275. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44276. if (this.environmentTexture) {
  44277. activeTextures.push(this.environmentTexture);
  44278. }
  44279. if (this.normalTexture) {
  44280. activeTextures.push(this.normalTexture);
  44281. }
  44282. if (this.emissiveTexture) {
  44283. activeTextures.push(this.emissiveTexture);
  44284. }
  44285. if (this.occlusionTexture) {
  44286. activeTextures.push(this.occlusionTexture);
  44287. }
  44288. if (this.lightmapTexture) {
  44289. activeTextures.push(this.lightmapTexture);
  44290. }
  44291. return activeTextures;
  44292. };
  44293. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44294. if (_super.prototype.hasTexture.call(this, texture)) {
  44295. return true;
  44296. }
  44297. if (this.lightmapTexture === texture) {
  44298. return true;
  44299. }
  44300. return false;
  44301. };
  44302. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44303. return "PBRBaseSimpleMaterial";
  44304. };
  44305. __decorate([
  44306. BABYLON.serialize(),
  44307. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44308. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44309. __decorate([
  44310. BABYLON.serialize(),
  44311. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44312. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44313. __decorate([
  44314. BABYLON.serializeAsTexture(),
  44315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44316. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44317. __decorate([
  44318. BABYLON.serialize(),
  44319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44320. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44321. __decorate([
  44322. BABYLON.serialize(),
  44323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44324. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44325. __decorate([
  44326. BABYLON.serializeAsTexture(),
  44327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44328. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44329. __decorate([
  44330. BABYLON.serializeAsColor3("emissive"),
  44331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44332. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44333. __decorate([
  44334. BABYLON.serializeAsTexture(),
  44335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44336. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44337. __decorate([
  44338. BABYLON.serialize(),
  44339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44340. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44341. __decorate([
  44342. BABYLON.serializeAsTexture(),
  44343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44344. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44345. __decorate([
  44346. BABYLON.serialize(),
  44347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44348. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44349. __decorate([
  44350. BABYLON.serialize()
  44351. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44352. __decorate([
  44353. BABYLON.serializeAsTexture(),
  44354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44355. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44356. __decorate([
  44357. BABYLON.serialize(),
  44358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44359. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44360. return PBRBaseSimpleMaterial;
  44361. }(BABYLON.PBRBaseMaterial));
  44362. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44363. })(BABYLON || (BABYLON = {}));
  44364. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44365. var BABYLON;
  44366. (function (BABYLON) {
  44367. /**
  44368. * The Physically based material of BJS.
  44369. *
  44370. * This offers the main features of a standard PBR material.
  44371. * For more information, please refer to the documentation :
  44372. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44373. */
  44374. var PBRMaterial = /** @class */ (function (_super) {
  44375. __extends(PBRMaterial, _super);
  44376. /**
  44377. * Instantiates a new PBRMaterial instance.
  44378. *
  44379. * @param name The material name
  44380. * @param scene The scene the material will be use in.
  44381. */
  44382. function PBRMaterial(name, scene) {
  44383. var _this = _super.call(this, name, scene) || this;
  44384. /**
  44385. * Intensity of the direct lights e.g. the four lights available in your scene.
  44386. * This impacts both the direct diffuse and specular highlights.
  44387. */
  44388. _this.directIntensity = 1.0;
  44389. /**
  44390. * Intensity of the emissive part of the material.
  44391. * This helps controlling the emissive effect without modifying the emissive color.
  44392. */
  44393. _this.emissiveIntensity = 1.0;
  44394. /**
  44395. * Intensity of the environment e.g. how much the environment will light the object
  44396. * either through harmonics for rough material or through the refelction for shiny ones.
  44397. */
  44398. _this.environmentIntensity = 1.0;
  44399. /**
  44400. * This is a special control allowing the reduction of the specular highlights coming from the
  44401. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44402. */
  44403. _this.specularIntensity = 1.0;
  44404. /**
  44405. * Debug Control allowing disabling the bump map on this material.
  44406. */
  44407. _this.disableBumpMap = false;
  44408. /**
  44409. * AKA Occlusion Texture Intensity in other nomenclature.
  44410. */
  44411. _this.ambientTextureStrength = 1.0;
  44412. /**
  44413. * The color of a material in ambient lighting.
  44414. */
  44415. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44416. /**
  44417. * AKA Diffuse Color in other nomenclature.
  44418. */
  44419. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44420. /**
  44421. * AKA Specular Color in other nomenclature.
  44422. */
  44423. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44424. /**
  44425. * The color reflected from the material.
  44426. */
  44427. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44428. /**
  44429. * The color emitted from the material.
  44430. */
  44431. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44432. /**
  44433. * AKA Glossiness in other nomenclature.
  44434. */
  44435. _this.microSurface = 1.0;
  44436. /**
  44437. * source material index of refraction (IOR)' / 'destination material IOR.
  44438. */
  44439. _this.indexOfRefraction = 0.66;
  44440. /**
  44441. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44442. */
  44443. _this.invertRefractionY = false;
  44444. /**
  44445. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44446. * Materials half opaque for instance using refraction could benefit from this control.
  44447. */
  44448. _this.linkRefractionWithTransparency = false;
  44449. _this.useLightmapAsShadowmap = false;
  44450. /**
  44451. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44452. */
  44453. _this.useAlphaFromAlbedoTexture = false;
  44454. /**
  44455. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44456. */
  44457. _this.forceAlphaTest = false;
  44458. /**
  44459. * Defines the alpha limits in alpha test mode.
  44460. */
  44461. _this.alphaCutOff = 0.4;
  44462. /**
  44463. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44464. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44465. */
  44466. _this.useSpecularOverAlpha = true;
  44467. /**
  44468. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44469. */
  44470. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44471. /**
  44472. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44473. */
  44474. _this.useRoughnessFromMetallicTextureAlpha = true;
  44475. /**
  44476. * Specifies if the metallic texture contains the roughness information in its green channel.
  44477. */
  44478. _this.useRoughnessFromMetallicTextureGreen = false;
  44479. /**
  44480. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44481. */
  44482. _this.useMetallnessFromMetallicTextureBlue = false;
  44483. /**
  44484. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44485. */
  44486. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44487. /**
  44488. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44489. */
  44490. _this.useAmbientInGrayScale = false;
  44491. /**
  44492. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44493. * The material will try to infer what glossiness each pixel should be.
  44494. */
  44495. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44496. /**
  44497. * BJS is using an harcoded light falloff based on a manually sets up range.
  44498. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44499. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44500. */
  44501. _this.usePhysicalLightFalloff = true;
  44502. /**
  44503. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44504. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44505. */
  44506. _this.useRadianceOverAlpha = true;
  44507. /**
  44508. * Allows using an object space normal map (instead of tangent space).
  44509. */
  44510. _this.useObjectSpaceNormalMap = false;
  44511. /**
  44512. * Allows using the bump map in parallax mode.
  44513. */
  44514. _this.useParallax = false;
  44515. /**
  44516. * Allows using the bump map in parallax occlusion mode.
  44517. */
  44518. _this.useParallaxOcclusion = false;
  44519. /**
  44520. * Controls the scale bias of the parallax mode.
  44521. */
  44522. _this.parallaxScaleBias = 0.05;
  44523. /**
  44524. * If sets to true, disables all the lights affecting the material.
  44525. */
  44526. _this.disableLighting = false;
  44527. /**
  44528. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44529. */
  44530. _this.forceIrradianceInFragment = false;
  44531. /**
  44532. * Number of Simultaneous lights allowed on the material.
  44533. */
  44534. _this.maxSimultaneousLights = 4;
  44535. /**
  44536. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44537. */
  44538. _this.invertNormalMapX = false;
  44539. /**
  44540. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44541. */
  44542. _this.invertNormalMapY = false;
  44543. /**
  44544. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44545. */
  44546. _this.twoSidedLighting = false;
  44547. /**
  44548. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44549. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44550. */
  44551. _this.useAlphaFresnel = false;
  44552. /**
  44553. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44554. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44555. */
  44556. _this.useLinearAlphaFresnel = false;
  44557. /**
  44558. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44559. * And/Or occlude the blended part.
  44560. */
  44561. _this.environmentBRDFTexture = null;
  44562. /**
  44563. * Force normal to face away from face.
  44564. */
  44565. _this.forceNormalForward = false;
  44566. /**
  44567. * Enables specular anti aliasing in the PBR shader.
  44568. * It will both interacts on the Geometry for analytical and IBL lighting.
  44569. * It also prefilter the roughness map based on the bump values.
  44570. */
  44571. _this.enableSpecularAntiAliasing = false;
  44572. /**
  44573. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44574. * makes the reflect vector face the model (under horizon).
  44575. */
  44576. _this.useHorizonOcclusion = true;
  44577. /**
  44578. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44579. * too much the area relying on ambient texture to define their ambient occlusion.
  44580. */
  44581. _this.useRadianceOcclusion = true;
  44582. /**
  44583. * If set to true, no lighting calculations will be applied.
  44584. */
  44585. _this.unlit = false;
  44586. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44587. return _this;
  44588. }
  44589. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44590. /**
  44591. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44592. */
  44593. get: function () {
  44594. return this._PBRMATERIAL_OPAQUE;
  44595. },
  44596. enumerable: true,
  44597. configurable: true
  44598. });
  44599. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44600. /**
  44601. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44602. */
  44603. get: function () {
  44604. return this._PBRMATERIAL_ALPHATEST;
  44605. },
  44606. enumerable: true,
  44607. configurable: true
  44608. });
  44609. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44610. /**
  44611. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44612. */
  44613. get: function () {
  44614. return this._PBRMATERIAL_ALPHABLEND;
  44615. },
  44616. enumerable: true,
  44617. configurable: true
  44618. });
  44619. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44620. /**
  44621. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44622. * They are also discarded below the alpha cutoff threshold to improve performances.
  44623. */
  44624. get: function () {
  44625. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44626. },
  44627. enumerable: true,
  44628. configurable: true
  44629. });
  44630. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44631. /**
  44632. * Gets the image processing configuration used either in this material.
  44633. */
  44634. get: function () {
  44635. return this._imageProcessingConfiguration;
  44636. },
  44637. /**
  44638. * Sets the Default image processing configuration used either in the this material.
  44639. *
  44640. * If sets to null, the scene one is in use.
  44641. */
  44642. set: function (value) {
  44643. this._attachImageProcessingConfiguration(value);
  44644. // Ensure the effect will be rebuilt.
  44645. this._markAllSubMeshesAsTexturesDirty();
  44646. },
  44647. enumerable: true,
  44648. configurable: true
  44649. });
  44650. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44651. /**
  44652. * Gets wether the color curves effect is enabled.
  44653. */
  44654. get: function () {
  44655. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44656. },
  44657. /**
  44658. * Sets wether the color curves effect is enabled.
  44659. */
  44660. set: function (value) {
  44661. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44662. },
  44663. enumerable: true,
  44664. configurable: true
  44665. });
  44666. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44667. /**
  44668. * Gets wether the color grading effect is enabled.
  44669. */
  44670. get: function () {
  44671. return this.imageProcessingConfiguration.colorGradingEnabled;
  44672. },
  44673. /**
  44674. * Gets wether the color grading effect is enabled.
  44675. */
  44676. set: function (value) {
  44677. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44678. },
  44679. enumerable: true,
  44680. configurable: true
  44681. });
  44682. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44683. /**
  44684. * Gets wether tonemapping is enabled or not.
  44685. */
  44686. get: function () {
  44687. return this._imageProcessingConfiguration.toneMappingEnabled;
  44688. },
  44689. /**
  44690. * Sets wether tonemapping is enabled or not
  44691. */
  44692. set: function (value) {
  44693. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44694. },
  44695. enumerable: true,
  44696. configurable: true
  44697. });
  44698. ;
  44699. ;
  44700. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44701. /**
  44702. * The camera exposure used on this material.
  44703. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44704. * This corresponds to a photographic exposure.
  44705. */
  44706. get: function () {
  44707. return this._imageProcessingConfiguration.exposure;
  44708. },
  44709. /**
  44710. * The camera exposure used on this material.
  44711. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44712. * This corresponds to a photographic exposure.
  44713. */
  44714. set: function (value) {
  44715. this._imageProcessingConfiguration.exposure = value;
  44716. },
  44717. enumerable: true,
  44718. configurable: true
  44719. });
  44720. ;
  44721. ;
  44722. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  44723. /**
  44724. * Gets The camera contrast used on this material.
  44725. */
  44726. get: function () {
  44727. return this._imageProcessingConfiguration.contrast;
  44728. },
  44729. /**
  44730. * Sets The camera contrast used on this material.
  44731. */
  44732. set: function (value) {
  44733. this._imageProcessingConfiguration.contrast = value;
  44734. },
  44735. enumerable: true,
  44736. configurable: true
  44737. });
  44738. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  44739. /**
  44740. * Gets the Color Grading 2D Lookup Texture.
  44741. */
  44742. get: function () {
  44743. return this._imageProcessingConfiguration.colorGradingTexture;
  44744. },
  44745. /**
  44746. * Sets the Color Grading 2D Lookup Texture.
  44747. */
  44748. set: function (value) {
  44749. this._imageProcessingConfiguration.colorGradingTexture = value;
  44750. },
  44751. enumerable: true,
  44752. configurable: true
  44753. });
  44754. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  44755. /**
  44756. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44757. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44758. * 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;
  44759. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44760. */
  44761. get: function () {
  44762. return this._imageProcessingConfiguration.colorCurves;
  44763. },
  44764. /**
  44765. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44766. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44767. * 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;
  44768. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44769. */
  44770. set: function (value) {
  44771. this._imageProcessingConfiguration.colorCurves = value;
  44772. },
  44773. enumerable: true,
  44774. configurable: true
  44775. });
  44776. /**
  44777. * Returns the name of this material class.
  44778. */
  44779. PBRMaterial.prototype.getClassName = function () {
  44780. return "PBRMaterial";
  44781. };
  44782. /**
  44783. * Returns an array of the actively used textures.
  44784. * @returns - Array of BaseTextures
  44785. */
  44786. PBRMaterial.prototype.getActiveTextures = function () {
  44787. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44788. if (this._albedoTexture) {
  44789. activeTextures.push(this._albedoTexture);
  44790. }
  44791. if (this._ambientTexture) {
  44792. activeTextures.push(this._ambientTexture);
  44793. }
  44794. if (this._opacityTexture) {
  44795. activeTextures.push(this._opacityTexture);
  44796. }
  44797. if (this._reflectionTexture) {
  44798. activeTextures.push(this._reflectionTexture);
  44799. }
  44800. if (this._emissiveTexture) {
  44801. activeTextures.push(this._emissiveTexture);
  44802. }
  44803. if (this._reflectivityTexture) {
  44804. activeTextures.push(this._reflectivityTexture);
  44805. }
  44806. if (this._metallicTexture) {
  44807. activeTextures.push(this._metallicTexture);
  44808. }
  44809. if (this._microSurfaceTexture) {
  44810. activeTextures.push(this._microSurfaceTexture);
  44811. }
  44812. if (this._bumpTexture) {
  44813. activeTextures.push(this._bumpTexture);
  44814. }
  44815. if (this._lightmapTexture) {
  44816. activeTextures.push(this._lightmapTexture);
  44817. }
  44818. if (this._refractionTexture) {
  44819. activeTextures.push(this._refractionTexture);
  44820. }
  44821. return activeTextures;
  44822. };
  44823. /**
  44824. * Checks to see if a texture is used in the material.
  44825. * @param texture - Base texture to use.
  44826. * @returns - Boolean specifying if a texture is used in the material.
  44827. */
  44828. PBRMaterial.prototype.hasTexture = function (texture) {
  44829. if (_super.prototype.hasTexture.call(this, texture)) {
  44830. return true;
  44831. }
  44832. if (this._albedoTexture === texture) {
  44833. return true;
  44834. }
  44835. if (this._ambientTexture === texture) {
  44836. return true;
  44837. }
  44838. if (this._opacityTexture === texture) {
  44839. return true;
  44840. }
  44841. if (this._reflectionTexture === texture) {
  44842. return true;
  44843. }
  44844. if (this._reflectivityTexture === texture) {
  44845. return true;
  44846. }
  44847. if (this._metallicTexture === texture) {
  44848. return true;
  44849. }
  44850. if (this._microSurfaceTexture === texture) {
  44851. return true;
  44852. }
  44853. if (this._bumpTexture === texture) {
  44854. return true;
  44855. }
  44856. if (this._lightmapTexture === texture) {
  44857. return true;
  44858. }
  44859. if (this._refractionTexture === texture) {
  44860. return true;
  44861. }
  44862. return false;
  44863. };
  44864. /**
  44865. * Makes a duplicate of the current material.
  44866. * @param name - name to use for the new material.
  44867. */
  44868. PBRMaterial.prototype.clone = function (name) {
  44869. var _this = this;
  44870. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  44871. clone.id = name;
  44872. clone.name = name;
  44873. return clone;
  44874. };
  44875. /**
  44876. * Serializes this PBR Material.
  44877. * @returns - An object with the serialized material.
  44878. */
  44879. PBRMaterial.prototype.serialize = function () {
  44880. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44881. serializationObject.customType = "BABYLON.PBRMaterial";
  44882. return serializationObject;
  44883. };
  44884. // Statics
  44885. /**
  44886. * Parses a PBR Material from a serialized object.
  44887. * @param source - Serialized object.
  44888. * @param scene - BJS scene instance.
  44889. * @param rootUrl - url for the scene object
  44890. * @returns - PBRMaterial
  44891. */
  44892. PBRMaterial.Parse = function (source, scene, rootUrl) {
  44893. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  44894. };
  44895. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  44896. /**
  44897. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44898. */
  44899. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  44900. /**
  44901. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44902. */
  44903. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  44904. /**
  44905. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44906. * They are also discarded below the alpha cutoff threshold to improve performances.
  44907. */
  44908. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  44909. __decorate([
  44910. BABYLON.serialize(),
  44911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44912. ], PBRMaterial.prototype, "directIntensity", void 0);
  44913. __decorate([
  44914. BABYLON.serialize(),
  44915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44916. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  44917. __decorate([
  44918. BABYLON.serialize(),
  44919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44920. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  44921. __decorate([
  44922. BABYLON.serialize(),
  44923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44924. ], PBRMaterial.prototype, "specularIntensity", void 0);
  44925. __decorate([
  44926. BABYLON.serialize(),
  44927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44928. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  44929. __decorate([
  44930. BABYLON.serializeAsTexture(),
  44931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44932. ], PBRMaterial.prototype, "albedoTexture", void 0);
  44933. __decorate([
  44934. BABYLON.serializeAsTexture(),
  44935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44936. ], PBRMaterial.prototype, "ambientTexture", void 0);
  44937. __decorate([
  44938. BABYLON.serialize(),
  44939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44940. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  44941. __decorate([
  44942. BABYLON.serializeAsTexture(),
  44943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44944. ], PBRMaterial.prototype, "opacityTexture", void 0);
  44945. __decorate([
  44946. BABYLON.serializeAsTexture(),
  44947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44948. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  44949. __decorate([
  44950. BABYLON.serializeAsTexture(),
  44951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44952. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  44953. __decorate([
  44954. BABYLON.serializeAsTexture(),
  44955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44956. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  44957. __decorate([
  44958. BABYLON.serializeAsTexture(),
  44959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44960. ], PBRMaterial.prototype, "metallicTexture", void 0);
  44961. __decorate([
  44962. BABYLON.serialize(),
  44963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44964. ], PBRMaterial.prototype, "metallic", void 0);
  44965. __decorate([
  44966. BABYLON.serialize(),
  44967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44968. ], PBRMaterial.prototype, "roughness", void 0);
  44969. __decorate([
  44970. BABYLON.serializeAsTexture(),
  44971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44972. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  44973. __decorate([
  44974. BABYLON.serializeAsTexture(),
  44975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44976. ], PBRMaterial.prototype, "bumpTexture", void 0);
  44977. __decorate([
  44978. BABYLON.serializeAsTexture(),
  44979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44980. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  44981. __decorate([
  44982. BABYLON.serializeAsTexture(),
  44983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44984. ], PBRMaterial.prototype, "refractionTexture", void 0);
  44985. __decorate([
  44986. BABYLON.serializeAsColor3("ambient"),
  44987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44988. ], PBRMaterial.prototype, "ambientColor", void 0);
  44989. __decorate([
  44990. BABYLON.serializeAsColor3("albedo"),
  44991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44992. ], PBRMaterial.prototype, "albedoColor", void 0);
  44993. __decorate([
  44994. BABYLON.serializeAsColor3("reflectivity"),
  44995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44996. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  44997. __decorate([
  44998. BABYLON.serializeAsColor3("reflection"),
  44999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45000. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45001. __decorate([
  45002. BABYLON.serializeAsColor3("emissive"),
  45003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45004. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45005. __decorate([
  45006. BABYLON.serialize(),
  45007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45008. ], PBRMaterial.prototype, "microSurface", void 0);
  45009. __decorate([
  45010. BABYLON.serialize(),
  45011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45012. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45013. __decorate([
  45014. BABYLON.serialize(),
  45015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45016. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45017. __decorate([
  45018. BABYLON.serialize(),
  45019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45020. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45021. __decorate([
  45022. BABYLON.serialize(),
  45023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45024. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45025. __decorate([
  45026. BABYLON.serialize(),
  45027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45028. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45029. __decorate([
  45030. BABYLON.serialize(),
  45031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45032. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45033. __decorate([
  45034. BABYLON.serialize(),
  45035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45036. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45037. __decorate([
  45038. BABYLON.serialize(),
  45039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45040. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45041. __decorate([
  45042. BABYLON.serialize(),
  45043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45044. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45045. __decorate([
  45046. BABYLON.serialize(),
  45047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45048. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45049. __decorate([
  45050. BABYLON.serialize(),
  45051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45052. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45053. __decorate([
  45054. BABYLON.serialize(),
  45055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45056. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45057. __decorate([
  45058. BABYLON.serialize(),
  45059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45060. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45061. __decorate([
  45062. BABYLON.serialize(),
  45063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45064. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45065. __decorate([
  45066. BABYLON.serialize(),
  45067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45068. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45069. __decorate([
  45070. BABYLON.serialize(),
  45071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45072. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45073. __decorate([
  45074. BABYLON.serialize(),
  45075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45076. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45077. __decorate([
  45078. BABYLON.serialize(),
  45079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45080. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45081. __decorate([
  45082. BABYLON.serialize(),
  45083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45084. ], PBRMaterial.prototype, "useParallax", void 0);
  45085. __decorate([
  45086. BABYLON.serialize(),
  45087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45088. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45089. __decorate([
  45090. BABYLON.serialize(),
  45091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45092. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45093. __decorate([
  45094. BABYLON.serialize(),
  45095. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45096. ], PBRMaterial.prototype, "disableLighting", void 0);
  45097. __decorate([
  45098. BABYLON.serialize(),
  45099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45100. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45101. __decorate([
  45102. BABYLON.serialize(),
  45103. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45104. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45105. __decorate([
  45106. BABYLON.serialize(),
  45107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45108. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45109. __decorate([
  45110. BABYLON.serialize(),
  45111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45112. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45113. __decorate([
  45114. BABYLON.serialize(),
  45115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45116. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45117. __decorate([
  45118. BABYLON.serialize(),
  45119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45120. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45121. __decorate([
  45122. BABYLON.serialize(),
  45123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45124. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45125. __decorate([
  45126. BABYLON.serializeAsTexture(),
  45127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45128. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45129. __decorate([
  45130. BABYLON.serialize(),
  45131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45132. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45133. __decorate([
  45134. BABYLON.serialize(),
  45135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45136. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45137. __decorate([
  45138. BABYLON.serialize(),
  45139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45140. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45141. __decorate([
  45142. BABYLON.serialize(),
  45143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45144. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45145. __decorate([
  45146. BABYLON.serialize(),
  45147. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45148. ], PBRMaterial.prototype, "unlit", void 0);
  45149. return PBRMaterial;
  45150. }(BABYLON.PBRBaseMaterial));
  45151. BABYLON.PBRMaterial = PBRMaterial;
  45152. })(BABYLON || (BABYLON = {}));
  45153. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45154. var BABYLON;
  45155. (function (BABYLON) {
  45156. /**
  45157. * The PBR material of BJS following the metal roughness convention.
  45158. *
  45159. * This fits to the PBR convention in the GLTF definition:
  45160. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45161. */
  45162. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45163. __extends(PBRMetallicRoughnessMaterial, _super);
  45164. /**
  45165. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45166. *
  45167. * @param name The material name
  45168. * @param scene The scene the material will be use in.
  45169. */
  45170. function PBRMetallicRoughnessMaterial(name, scene) {
  45171. var _this = _super.call(this, name, scene) || this;
  45172. _this._useRoughnessFromMetallicTextureAlpha = false;
  45173. _this._useRoughnessFromMetallicTextureGreen = true;
  45174. _this._useMetallnessFromMetallicTextureBlue = true;
  45175. _this.metallic = 1.0;
  45176. _this.roughness = 1.0;
  45177. return _this;
  45178. }
  45179. /**
  45180. * Return the currrent class name of the material.
  45181. */
  45182. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45183. return "PBRMetallicRoughnessMaterial";
  45184. };
  45185. /**
  45186. * Return the active textures of the material.
  45187. */
  45188. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45189. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45190. if (this.baseTexture) {
  45191. activeTextures.push(this.baseTexture);
  45192. }
  45193. if (this.metallicRoughnessTexture) {
  45194. activeTextures.push(this.metallicRoughnessTexture);
  45195. }
  45196. return activeTextures;
  45197. };
  45198. /**
  45199. * Checks to see if a texture is used in the material.
  45200. * @param texture - Base texture to use.
  45201. * @returns - Boolean specifying if a texture is used in the material.
  45202. */
  45203. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45204. if (_super.prototype.hasTexture.call(this, texture)) {
  45205. return true;
  45206. }
  45207. if (this.baseTexture === texture) {
  45208. return true;
  45209. }
  45210. if (this.metallicRoughnessTexture === texture) {
  45211. return true;
  45212. }
  45213. return false;
  45214. };
  45215. /**
  45216. * Makes a duplicate of the current material.
  45217. * @param name - name to use for the new material.
  45218. */
  45219. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45220. var _this = this;
  45221. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45222. clone.id = name;
  45223. clone.name = name;
  45224. return clone;
  45225. };
  45226. /**
  45227. * Serialize the material to a parsable JSON object.
  45228. */
  45229. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45230. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45231. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45232. return serializationObject;
  45233. };
  45234. /**
  45235. * Parses a JSON object correponding to the serialize function.
  45236. */
  45237. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45238. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45239. };
  45240. __decorate([
  45241. BABYLON.serializeAsColor3(),
  45242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45243. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45244. __decorate([
  45245. BABYLON.serializeAsTexture(),
  45246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45247. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45248. __decorate([
  45249. BABYLON.serialize(),
  45250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45251. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45252. __decorate([
  45253. BABYLON.serialize(),
  45254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45255. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45256. __decorate([
  45257. BABYLON.serializeAsTexture(),
  45258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45259. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45260. return PBRMetallicRoughnessMaterial;
  45261. }(BABYLON.PBRBaseSimpleMaterial));
  45262. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45263. })(BABYLON || (BABYLON = {}));
  45264. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45265. var BABYLON;
  45266. (function (BABYLON) {
  45267. /**
  45268. * The PBR material of BJS following the specular glossiness convention.
  45269. *
  45270. * This fits to the PBR convention in the GLTF definition:
  45271. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45272. */
  45273. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45274. __extends(PBRSpecularGlossinessMaterial, _super);
  45275. /**
  45276. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45277. *
  45278. * @param name The material name
  45279. * @param scene The scene the material will be use in.
  45280. */
  45281. function PBRSpecularGlossinessMaterial(name, scene) {
  45282. var _this = _super.call(this, name, scene) || this;
  45283. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45284. return _this;
  45285. }
  45286. /**
  45287. * Return the currrent class name of the material.
  45288. */
  45289. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45290. return "PBRSpecularGlossinessMaterial";
  45291. };
  45292. /**
  45293. * Return the active textures of the material.
  45294. */
  45295. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45296. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45297. if (this.diffuseTexture) {
  45298. activeTextures.push(this.diffuseTexture);
  45299. }
  45300. if (this.specularGlossinessTexture) {
  45301. activeTextures.push(this.specularGlossinessTexture);
  45302. }
  45303. return activeTextures;
  45304. };
  45305. /**
  45306. * Checks to see if a texture is used in the material.
  45307. * @param texture - Base texture to use.
  45308. * @returns - Boolean specifying if a texture is used in the material.
  45309. */
  45310. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45311. if (_super.prototype.hasTexture.call(this, texture)) {
  45312. return true;
  45313. }
  45314. if (this.diffuseTexture === texture) {
  45315. return true;
  45316. }
  45317. if (this.specularGlossinessTexture === texture) {
  45318. return true;
  45319. }
  45320. return false;
  45321. };
  45322. /**
  45323. * Makes a duplicate of the current material.
  45324. * @param name - name to use for the new material.
  45325. */
  45326. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45327. var _this = this;
  45328. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45329. clone.id = name;
  45330. clone.name = name;
  45331. return clone;
  45332. };
  45333. /**
  45334. * Serialize the material to a parsable JSON object.
  45335. */
  45336. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45337. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45338. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45339. return serializationObject;
  45340. };
  45341. /**
  45342. * Parses a JSON object correponding to the serialize function.
  45343. */
  45344. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45345. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45346. };
  45347. __decorate([
  45348. BABYLON.serializeAsColor3("diffuse"),
  45349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45350. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45351. __decorate([
  45352. BABYLON.serializeAsTexture(),
  45353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45354. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45355. __decorate([
  45356. BABYLON.serializeAsColor3("specular"),
  45357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45358. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45359. __decorate([
  45360. BABYLON.serialize(),
  45361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45362. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45363. __decorate([
  45364. BABYLON.serializeAsTexture(),
  45365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45366. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45367. return PBRSpecularGlossinessMaterial;
  45368. }(BABYLON.PBRBaseSimpleMaterial));
  45369. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45370. })(BABYLON || (BABYLON = {}));
  45371. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45372. var BABYLON;
  45373. (function (BABYLON) {
  45374. BABYLON.CameraInputTypes = {};
  45375. var CameraInputsManager = /** @class */ (function () {
  45376. function CameraInputsManager(camera) {
  45377. this.attached = {};
  45378. this.camera = camera;
  45379. this.checkInputs = function () { };
  45380. }
  45381. /**
  45382. * Add an input method to a camera
  45383. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45384. * @param input camera input method
  45385. */
  45386. CameraInputsManager.prototype.add = function (input) {
  45387. var type = input.getSimpleName();
  45388. if (this.attached[type]) {
  45389. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45390. return;
  45391. }
  45392. this.attached[type] = input;
  45393. input.camera = this.camera;
  45394. //for checkInputs, we are dynamically creating a function
  45395. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45396. if (input.checkInputs) {
  45397. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45398. }
  45399. if (this.attachedElement) {
  45400. input.attachControl(this.attachedElement);
  45401. }
  45402. };
  45403. /**
  45404. * Remove a specific input method from a camera
  45405. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45406. * @param inputToRemove camera input method
  45407. */
  45408. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45409. for (var cam in this.attached) {
  45410. var input = this.attached[cam];
  45411. if (input === inputToRemove) {
  45412. input.detachControl(this.attachedElement);
  45413. input.camera = null;
  45414. delete this.attached[cam];
  45415. this.rebuildInputCheck();
  45416. }
  45417. }
  45418. };
  45419. CameraInputsManager.prototype.removeByType = function (inputType) {
  45420. for (var cam in this.attached) {
  45421. var input = this.attached[cam];
  45422. if (input.getClassName() === inputType) {
  45423. input.detachControl(this.attachedElement);
  45424. input.camera = null;
  45425. delete this.attached[cam];
  45426. this.rebuildInputCheck();
  45427. }
  45428. }
  45429. };
  45430. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45431. var current = this.checkInputs;
  45432. return function () {
  45433. current();
  45434. fn();
  45435. };
  45436. };
  45437. CameraInputsManager.prototype.attachInput = function (input) {
  45438. if (this.attachedElement) {
  45439. input.attachControl(this.attachedElement, this.noPreventDefault);
  45440. }
  45441. };
  45442. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45443. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45444. if (this.attachedElement) {
  45445. return;
  45446. }
  45447. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45448. this.attachedElement = element;
  45449. this.noPreventDefault = noPreventDefault;
  45450. for (var cam in this.attached) {
  45451. this.attached[cam].attachControl(element, noPreventDefault);
  45452. }
  45453. };
  45454. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45455. if (disconnect === void 0) { disconnect = false; }
  45456. if (this.attachedElement !== element) {
  45457. return;
  45458. }
  45459. for (var cam in this.attached) {
  45460. this.attached[cam].detachControl(element);
  45461. if (disconnect) {
  45462. this.attached[cam].camera = null;
  45463. }
  45464. }
  45465. this.attachedElement = null;
  45466. };
  45467. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45468. this.checkInputs = function () { };
  45469. for (var cam in this.attached) {
  45470. var input = this.attached[cam];
  45471. if (input.checkInputs) {
  45472. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45473. }
  45474. }
  45475. };
  45476. /**
  45477. * Remove all attached input methods from a camera
  45478. */
  45479. CameraInputsManager.prototype.clear = function () {
  45480. if (this.attachedElement) {
  45481. this.detachElement(this.attachedElement, true);
  45482. }
  45483. this.attached = {};
  45484. this.attachedElement = null;
  45485. this.checkInputs = function () { };
  45486. };
  45487. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45488. var inputs = {};
  45489. for (var cam in this.attached) {
  45490. var input = this.attached[cam];
  45491. var res = BABYLON.SerializationHelper.Serialize(input);
  45492. inputs[input.getClassName()] = res;
  45493. }
  45494. serializedCamera.inputsmgr = inputs;
  45495. };
  45496. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45497. var parsedInputs = parsedCamera.inputsmgr;
  45498. if (parsedInputs) {
  45499. this.clear();
  45500. for (var n in parsedInputs) {
  45501. var construct = BABYLON.CameraInputTypes[n];
  45502. if (construct) {
  45503. var parsedinput = parsedInputs[n];
  45504. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45505. this.add(input);
  45506. }
  45507. }
  45508. }
  45509. else {
  45510. //2016-03-08 this part is for managing backward compatibility
  45511. for (var n in this.attached) {
  45512. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45513. if (construct) {
  45514. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45515. this.remove(this.attached[n]);
  45516. this.add(input);
  45517. }
  45518. }
  45519. }
  45520. };
  45521. return CameraInputsManager;
  45522. }());
  45523. BABYLON.CameraInputsManager = CameraInputsManager;
  45524. })(BABYLON || (BABYLON = {}));
  45525. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45526. var BABYLON;
  45527. (function (BABYLON) {
  45528. var TargetCamera = /** @class */ (function (_super) {
  45529. __extends(TargetCamera, _super);
  45530. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45531. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45532. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45533. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45534. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45535. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45536. _this.speed = 2.0;
  45537. _this.noRotationConstraint = false;
  45538. _this.lockedTarget = null;
  45539. _this._currentTarget = BABYLON.Vector3.Zero();
  45540. _this._viewMatrix = BABYLON.Matrix.Zero();
  45541. _this._camMatrix = BABYLON.Matrix.Zero();
  45542. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45543. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45544. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45545. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45546. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45547. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45548. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45549. return _this;
  45550. }
  45551. TargetCamera.prototype.getFrontPosition = function (distance) {
  45552. this.getWorldMatrix();
  45553. var direction = this.getTarget().subtract(this.position);
  45554. direction.normalize();
  45555. direction.scaleInPlace(distance);
  45556. return this.globalPosition.add(direction);
  45557. };
  45558. TargetCamera.prototype._getLockedTargetPosition = function () {
  45559. if (!this.lockedTarget) {
  45560. return null;
  45561. }
  45562. if (this.lockedTarget.absolutePosition) {
  45563. this.lockedTarget.computeWorldMatrix();
  45564. }
  45565. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45566. };
  45567. TargetCamera.prototype.storeState = function () {
  45568. this._storedPosition = this.position.clone();
  45569. this._storedRotation = this.rotation.clone();
  45570. if (this.rotationQuaternion) {
  45571. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45572. }
  45573. return _super.prototype.storeState.call(this);
  45574. };
  45575. /**
  45576. * Restored camera state. You must call storeState() first
  45577. */
  45578. TargetCamera.prototype._restoreStateValues = function () {
  45579. if (!_super.prototype._restoreStateValues.call(this)) {
  45580. return false;
  45581. }
  45582. this.position = this._storedPosition.clone();
  45583. this.rotation = this._storedRotation.clone();
  45584. if (this.rotationQuaternion) {
  45585. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45586. }
  45587. this.cameraDirection.copyFromFloats(0, 0, 0);
  45588. this.cameraRotation.copyFromFloats(0, 0);
  45589. return true;
  45590. };
  45591. // Cache
  45592. TargetCamera.prototype._initCache = function () {
  45593. _super.prototype._initCache.call(this);
  45594. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45595. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45596. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45597. };
  45598. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45599. if (!ignoreParentClass) {
  45600. _super.prototype._updateCache.call(this);
  45601. }
  45602. var lockedTargetPosition = this._getLockedTargetPosition();
  45603. if (!lockedTargetPosition) {
  45604. this._cache.lockedTarget = null;
  45605. }
  45606. else {
  45607. if (!this._cache.lockedTarget) {
  45608. this._cache.lockedTarget = lockedTargetPosition.clone();
  45609. }
  45610. else {
  45611. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45612. }
  45613. }
  45614. this._cache.rotation.copyFrom(this.rotation);
  45615. if (this.rotationQuaternion)
  45616. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45617. };
  45618. // Synchronized
  45619. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45620. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45621. return false;
  45622. }
  45623. var lockedTargetPosition = this._getLockedTargetPosition();
  45624. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45625. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45626. };
  45627. // Methods
  45628. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45629. var engine = this.getEngine();
  45630. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45631. };
  45632. // Target
  45633. TargetCamera.prototype.setTarget = function (target) {
  45634. this.upVector.normalize();
  45635. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45636. this._camMatrix.invert();
  45637. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45638. var vDir = target.subtract(this.position);
  45639. if (vDir.x >= 0.0) {
  45640. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45641. }
  45642. else {
  45643. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45644. }
  45645. this.rotation.z = 0;
  45646. if (isNaN(this.rotation.x)) {
  45647. this.rotation.x = 0;
  45648. }
  45649. if (isNaN(this.rotation.y)) {
  45650. this.rotation.y = 0;
  45651. }
  45652. if (isNaN(this.rotation.z)) {
  45653. this.rotation.z = 0;
  45654. }
  45655. if (this.rotationQuaternion) {
  45656. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45657. }
  45658. };
  45659. /**
  45660. * Return the current target position of the camera. This value is expressed in local space.
  45661. */
  45662. TargetCamera.prototype.getTarget = function () {
  45663. return this._currentTarget;
  45664. };
  45665. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45666. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45667. };
  45668. TargetCamera.prototype._updatePosition = function () {
  45669. if (this.parent) {
  45670. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45671. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45672. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45673. return;
  45674. }
  45675. this.position.addInPlace(this.cameraDirection);
  45676. };
  45677. TargetCamera.prototype._checkInputs = function () {
  45678. var needToMove = this._decideIfNeedsToMove();
  45679. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45680. // Move
  45681. if (needToMove) {
  45682. this._updatePosition();
  45683. }
  45684. // Rotate
  45685. if (needToRotate) {
  45686. this.rotation.x += this.cameraRotation.x;
  45687. this.rotation.y += this.cameraRotation.y;
  45688. //rotate, if quaternion is set and rotation was used
  45689. if (this.rotationQuaternion) {
  45690. var len = this.rotation.lengthSquared();
  45691. if (len) {
  45692. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45693. }
  45694. }
  45695. if (!this.noRotationConstraint) {
  45696. var limit = (Math.PI / 2) * 0.95;
  45697. if (this.rotation.x > limit)
  45698. this.rotation.x = limit;
  45699. if (this.rotation.x < -limit)
  45700. this.rotation.x = -limit;
  45701. }
  45702. }
  45703. // Inertia
  45704. if (needToMove) {
  45705. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45706. this.cameraDirection.x = 0;
  45707. }
  45708. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  45709. this.cameraDirection.y = 0;
  45710. }
  45711. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  45712. this.cameraDirection.z = 0;
  45713. }
  45714. this.cameraDirection.scaleInPlace(this.inertia);
  45715. }
  45716. if (needToRotate) {
  45717. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  45718. this.cameraRotation.x = 0;
  45719. }
  45720. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  45721. this.cameraRotation.y = 0;
  45722. }
  45723. this.cameraRotation.scaleInPlace(this.inertia);
  45724. }
  45725. _super.prototype._checkInputs.call(this);
  45726. };
  45727. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  45728. if (this.rotationQuaternion) {
  45729. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  45730. }
  45731. else {
  45732. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  45733. }
  45734. //update the up vector!
  45735. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  45736. };
  45737. TargetCamera.prototype._getViewMatrix = function () {
  45738. if (this.lockedTarget) {
  45739. this.setTarget(this._getLockedTargetPosition());
  45740. }
  45741. // Compute
  45742. this._updateCameraRotationMatrix();
  45743. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  45744. // Computing target and final matrix
  45745. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  45746. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  45747. return this._viewMatrix;
  45748. };
  45749. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  45750. if (this.parent) {
  45751. var parentWorldMatrix = this.parent.getWorldMatrix();
  45752. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  45753. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  45754. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  45755. this._markSyncedWithParent();
  45756. }
  45757. else {
  45758. this._globalPosition.copyFrom(this.position);
  45759. this._globalCurrentTarget.copyFrom(target);
  45760. this._globalCurrentUpVector.copyFrom(up);
  45761. }
  45762. if (this.getScene().useRightHandedSystem) {
  45763. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45764. }
  45765. else {
  45766. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45767. }
  45768. };
  45769. /**
  45770. * @override
  45771. * Override Camera.createRigCamera
  45772. */
  45773. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45774. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  45775. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  45776. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  45777. if (!this.rotationQuaternion) {
  45778. this.rotationQuaternion = new BABYLON.Quaternion();
  45779. }
  45780. rigCamera._cameraRigParams = {};
  45781. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  45782. }
  45783. return rigCamera;
  45784. }
  45785. return null;
  45786. };
  45787. /**
  45788. * @override
  45789. * Override Camera._updateRigCameras
  45790. */
  45791. TargetCamera.prototype._updateRigCameras = function () {
  45792. var camLeft = this._rigCameras[0];
  45793. var camRight = this._rigCameras[1];
  45794. switch (this.cameraRigMode) {
  45795. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45796. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45797. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45798. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45799. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  45800. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  45801. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  45802. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  45803. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  45804. camLeft.setTarget(this.getTarget());
  45805. camRight.setTarget(this.getTarget());
  45806. break;
  45807. case BABYLON.Camera.RIG_MODE_VR:
  45808. if (camLeft.rotationQuaternion) {
  45809. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45810. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45811. }
  45812. else {
  45813. camLeft.rotation.copyFrom(this.rotation);
  45814. camRight.rotation.copyFrom(this.rotation);
  45815. }
  45816. camLeft.position.copyFrom(this.position);
  45817. camRight.position.copyFrom(this.position);
  45818. break;
  45819. }
  45820. _super.prototype._updateRigCameras.call(this);
  45821. };
  45822. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  45823. if (!this._rigCamTransformMatrix) {
  45824. this._rigCamTransformMatrix = new BABYLON.Matrix();
  45825. }
  45826. var target = this.getTarget();
  45827. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  45828. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  45829. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  45830. };
  45831. TargetCamera.prototype.getClassName = function () {
  45832. return "TargetCamera";
  45833. };
  45834. __decorate([
  45835. BABYLON.serializeAsVector3()
  45836. ], TargetCamera.prototype, "rotation", void 0);
  45837. __decorate([
  45838. BABYLON.serialize()
  45839. ], TargetCamera.prototype, "speed", void 0);
  45840. __decorate([
  45841. BABYLON.serializeAsMeshReference("lockedTargetId")
  45842. ], TargetCamera.prototype, "lockedTarget", void 0);
  45843. return TargetCamera;
  45844. }(BABYLON.Camera));
  45845. BABYLON.TargetCamera = TargetCamera;
  45846. })(BABYLON || (BABYLON = {}));
  45847. //# sourceMappingURL=babylon.targetCamera.js.map
  45848. var BABYLON;
  45849. (function (BABYLON) {
  45850. var FreeCameraMouseInput = /** @class */ (function () {
  45851. function FreeCameraMouseInput(touchEnabled) {
  45852. if (touchEnabled === void 0) { touchEnabled = true; }
  45853. this.touchEnabled = touchEnabled;
  45854. this.buttons = [0, 1, 2];
  45855. this.angularSensibility = 2000.0;
  45856. this.previousPosition = null;
  45857. }
  45858. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  45859. var _this = this;
  45860. var engine = this.camera.getEngine();
  45861. if (!this._pointerInput) {
  45862. this._pointerInput = function (p, s) {
  45863. var evt = p.event;
  45864. if (engine.isInVRExclusivePointerMode) {
  45865. return;
  45866. }
  45867. if (!_this.touchEnabled && evt.pointerType === "touch") {
  45868. return;
  45869. }
  45870. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  45871. return;
  45872. }
  45873. var srcElement = (evt.srcElement || evt.target);
  45874. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  45875. try {
  45876. srcElement.setPointerCapture(evt.pointerId);
  45877. }
  45878. catch (e) {
  45879. //Nothing to do with the error. Execution will continue.
  45880. }
  45881. _this.previousPosition = {
  45882. x: evt.clientX,
  45883. y: evt.clientY
  45884. };
  45885. if (!noPreventDefault) {
  45886. evt.preventDefault();
  45887. element.focus();
  45888. }
  45889. }
  45890. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  45891. try {
  45892. srcElement.releasePointerCapture(evt.pointerId);
  45893. }
  45894. catch (e) {
  45895. //Nothing to do with the error.
  45896. }
  45897. _this.previousPosition = null;
  45898. if (!noPreventDefault) {
  45899. evt.preventDefault();
  45900. }
  45901. }
  45902. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45903. if (!_this.previousPosition || engine.isPointerLock) {
  45904. return;
  45905. }
  45906. var offsetX = evt.clientX - _this.previousPosition.x;
  45907. if (_this.camera.getScene().useRightHandedSystem)
  45908. offsetX *= -1;
  45909. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  45910. offsetX *= -1;
  45911. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  45912. var offsetY = evt.clientY - _this.previousPosition.y;
  45913. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  45914. _this.previousPosition = {
  45915. x: evt.clientX,
  45916. y: evt.clientY
  45917. };
  45918. if (!noPreventDefault) {
  45919. evt.preventDefault();
  45920. }
  45921. }
  45922. };
  45923. }
  45924. this._onMouseMove = function (evt) {
  45925. if (!engine.isPointerLock) {
  45926. return;
  45927. }
  45928. if (engine.isInVRExclusivePointerMode) {
  45929. return;
  45930. }
  45931. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  45932. if (_this.camera.getScene().useRightHandedSystem)
  45933. offsetX *= -1;
  45934. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  45935. offsetX *= -1;
  45936. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  45937. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  45938. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  45939. _this.previousPosition = null;
  45940. if (!noPreventDefault) {
  45941. evt.preventDefault();
  45942. }
  45943. };
  45944. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  45945. element.addEventListener("mousemove", this._onMouseMove, false);
  45946. };
  45947. FreeCameraMouseInput.prototype.detachControl = function (element) {
  45948. if (this._observer && element) {
  45949. this.camera.getScene().onPointerObservable.remove(this._observer);
  45950. if (this._onMouseMove) {
  45951. element.removeEventListener("mousemove", this._onMouseMove);
  45952. }
  45953. this._observer = null;
  45954. this._onMouseMove = null;
  45955. this.previousPosition = null;
  45956. }
  45957. };
  45958. FreeCameraMouseInput.prototype.getClassName = function () {
  45959. return "FreeCameraMouseInput";
  45960. };
  45961. FreeCameraMouseInput.prototype.getSimpleName = function () {
  45962. return "mouse";
  45963. };
  45964. __decorate([
  45965. BABYLON.serialize()
  45966. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  45967. __decorate([
  45968. BABYLON.serialize()
  45969. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  45970. return FreeCameraMouseInput;
  45971. }());
  45972. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  45973. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  45974. })(BABYLON || (BABYLON = {}));
  45975. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  45976. var BABYLON;
  45977. (function (BABYLON) {
  45978. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  45979. function FreeCameraKeyboardMoveInput() {
  45980. this._keys = new Array();
  45981. this.keysUp = [38];
  45982. this.keysDown = [40];
  45983. this.keysLeft = [37];
  45984. this.keysRight = [39];
  45985. }
  45986. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  45987. var _this = this;
  45988. if (this._onCanvasBlurObserver) {
  45989. return;
  45990. }
  45991. this._scene = this.camera.getScene();
  45992. this._engine = this._scene.getEngine();
  45993. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  45994. _this._keys = [];
  45995. });
  45996. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  45997. var evt = info.event;
  45998. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  45999. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46000. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46001. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46002. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46003. var index = _this._keys.indexOf(evt.keyCode);
  46004. if (index === -1) {
  46005. _this._keys.push(evt.keyCode);
  46006. }
  46007. if (!noPreventDefault) {
  46008. evt.preventDefault();
  46009. }
  46010. }
  46011. }
  46012. else {
  46013. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46014. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46015. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46016. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46017. var index = _this._keys.indexOf(evt.keyCode);
  46018. if (index >= 0) {
  46019. _this._keys.splice(index, 1);
  46020. }
  46021. if (!noPreventDefault) {
  46022. evt.preventDefault();
  46023. }
  46024. }
  46025. }
  46026. });
  46027. };
  46028. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46029. if (this._scene) {
  46030. if (this._onKeyboardObserver) {
  46031. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46032. }
  46033. if (this._onCanvasBlurObserver) {
  46034. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46035. }
  46036. this._onKeyboardObserver = null;
  46037. this._onCanvasBlurObserver = null;
  46038. }
  46039. this._keys = [];
  46040. };
  46041. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46042. if (this._onKeyboardObserver) {
  46043. var camera = this.camera;
  46044. // Keyboard
  46045. for (var index = 0; index < this._keys.length; index++) {
  46046. var keyCode = this._keys[index];
  46047. var speed = camera._computeLocalCameraSpeed();
  46048. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46049. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46050. }
  46051. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46052. camera._localDirection.copyFromFloats(0, 0, speed);
  46053. }
  46054. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46055. camera._localDirection.copyFromFloats(speed, 0, 0);
  46056. }
  46057. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46058. camera._localDirection.copyFromFloats(0, 0, -speed);
  46059. }
  46060. if (camera.getScene().useRightHandedSystem) {
  46061. camera._localDirection.z *= -1;
  46062. }
  46063. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46064. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46065. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46066. }
  46067. }
  46068. };
  46069. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46070. return "FreeCameraKeyboardMoveInput";
  46071. };
  46072. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46073. this._keys = [];
  46074. };
  46075. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46076. return "keyboard";
  46077. };
  46078. __decorate([
  46079. BABYLON.serialize()
  46080. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46081. __decorate([
  46082. BABYLON.serialize()
  46083. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46084. __decorate([
  46085. BABYLON.serialize()
  46086. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46087. __decorate([
  46088. BABYLON.serialize()
  46089. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46090. return FreeCameraKeyboardMoveInput;
  46091. }());
  46092. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46093. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46094. })(BABYLON || (BABYLON = {}));
  46095. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46096. var BABYLON;
  46097. (function (BABYLON) {
  46098. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46099. __extends(FreeCameraInputsManager, _super);
  46100. function FreeCameraInputsManager(camera) {
  46101. return _super.call(this, camera) || this;
  46102. }
  46103. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46104. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46105. return this;
  46106. };
  46107. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46108. if (touchEnabled === void 0) { touchEnabled = true; }
  46109. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46110. return this;
  46111. };
  46112. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46113. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46114. return this;
  46115. };
  46116. FreeCameraInputsManager.prototype.addTouch = function () {
  46117. this.add(new BABYLON.FreeCameraTouchInput());
  46118. return this;
  46119. };
  46120. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46121. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46122. return this;
  46123. };
  46124. return FreeCameraInputsManager;
  46125. }(BABYLON.CameraInputsManager));
  46126. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46127. })(BABYLON || (BABYLON = {}));
  46128. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46129. var BABYLON;
  46130. (function (BABYLON) {
  46131. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46132. // Forcing to use the Universal camera
  46133. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46134. });
  46135. var FreeCamera = /** @class */ (function (_super) {
  46136. __extends(FreeCamera, _super);
  46137. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46138. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46139. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46140. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46141. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46142. _this.checkCollisions = false;
  46143. _this.applyGravity = false;
  46144. _this._needMoveForGravity = false;
  46145. _this._oldPosition = BABYLON.Vector3.Zero();
  46146. _this._diffPosition = BABYLON.Vector3.Zero();
  46147. _this._newPosition = BABYLON.Vector3.Zero();
  46148. // Collisions
  46149. _this._collisionMask = -1;
  46150. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46151. if (collidedMesh === void 0) { collidedMesh = null; }
  46152. //TODO move this to the collision coordinator!
  46153. if (_this.getScene().workerCollisions)
  46154. newPosition.multiplyInPlace(_this._collider._radius);
  46155. var updatePosition = function (newPos) {
  46156. _this._newPosition.copyFrom(newPos);
  46157. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46158. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46159. _this.position.addInPlace(_this._diffPosition);
  46160. if (_this.onCollide && collidedMesh) {
  46161. _this.onCollide(collidedMesh);
  46162. }
  46163. }
  46164. };
  46165. updatePosition(newPosition);
  46166. };
  46167. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46168. _this.inputs.addKeyboard().addMouse();
  46169. return _this;
  46170. }
  46171. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46172. //-- begin properties for backward compatibility for inputs
  46173. /**
  46174. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46175. * Higher values reduce sensitivity.
  46176. */
  46177. get: function () {
  46178. var mouse = this.inputs.attached["mouse"];
  46179. if (mouse)
  46180. return mouse.angularSensibility;
  46181. return 0;
  46182. },
  46183. /**
  46184. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46185. * Higher values reduce sensitivity.
  46186. */
  46187. set: function (value) {
  46188. var mouse = this.inputs.attached["mouse"];
  46189. if (mouse)
  46190. mouse.angularSensibility = value;
  46191. },
  46192. enumerable: true,
  46193. configurable: true
  46194. });
  46195. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46196. get: function () {
  46197. var keyboard = this.inputs.attached["keyboard"];
  46198. if (keyboard)
  46199. return keyboard.keysUp;
  46200. return [];
  46201. },
  46202. set: function (value) {
  46203. var keyboard = this.inputs.attached["keyboard"];
  46204. if (keyboard)
  46205. keyboard.keysUp = value;
  46206. },
  46207. enumerable: true,
  46208. configurable: true
  46209. });
  46210. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46211. get: function () {
  46212. var keyboard = this.inputs.attached["keyboard"];
  46213. if (keyboard)
  46214. return keyboard.keysDown;
  46215. return [];
  46216. },
  46217. set: function (value) {
  46218. var keyboard = this.inputs.attached["keyboard"];
  46219. if (keyboard)
  46220. keyboard.keysDown = value;
  46221. },
  46222. enumerable: true,
  46223. configurable: true
  46224. });
  46225. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46226. get: function () {
  46227. var keyboard = this.inputs.attached["keyboard"];
  46228. if (keyboard)
  46229. return keyboard.keysLeft;
  46230. return [];
  46231. },
  46232. set: function (value) {
  46233. var keyboard = this.inputs.attached["keyboard"];
  46234. if (keyboard)
  46235. keyboard.keysLeft = value;
  46236. },
  46237. enumerable: true,
  46238. configurable: true
  46239. });
  46240. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46241. get: function () {
  46242. var keyboard = this.inputs.attached["keyboard"];
  46243. if (keyboard)
  46244. return keyboard.keysRight;
  46245. return [];
  46246. },
  46247. set: function (value) {
  46248. var keyboard = this.inputs.attached["keyboard"];
  46249. if (keyboard)
  46250. keyboard.keysRight = value;
  46251. },
  46252. enumerable: true,
  46253. configurable: true
  46254. });
  46255. // Controls
  46256. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46257. this.inputs.attachElement(element, noPreventDefault);
  46258. };
  46259. FreeCamera.prototype.detachControl = function (element) {
  46260. this.inputs.detachElement(element);
  46261. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46262. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46263. };
  46264. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46265. get: function () {
  46266. return this._collisionMask;
  46267. },
  46268. set: function (mask) {
  46269. this._collisionMask = !isNaN(mask) ? mask : -1;
  46270. },
  46271. enumerable: true,
  46272. configurable: true
  46273. });
  46274. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46275. var globalPosition;
  46276. if (this.parent) {
  46277. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46278. }
  46279. else {
  46280. globalPosition = this.position;
  46281. }
  46282. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46283. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46284. if (!this._collider) {
  46285. this._collider = new BABYLON.Collider();
  46286. }
  46287. this._collider._radius = this.ellipsoid;
  46288. this._collider.collisionMask = this._collisionMask;
  46289. //no need for clone, as long as gravity is not on.
  46290. var actualDisplacement = displacement;
  46291. //add gravity to the direction to prevent the dual-collision checking
  46292. if (this.applyGravity) {
  46293. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46294. actualDisplacement = displacement.add(this.getScene().gravity);
  46295. }
  46296. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46297. };
  46298. FreeCamera.prototype._checkInputs = function () {
  46299. if (!this._localDirection) {
  46300. this._localDirection = BABYLON.Vector3.Zero();
  46301. this._transformedDirection = BABYLON.Vector3.Zero();
  46302. }
  46303. this.inputs.checkInputs();
  46304. _super.prototype._checkInputs.call(this);
  46305. };
  46306. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46307. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46308. };
  46309. FreeCamera.prototype._updatePosition = function () {
  46310. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46311. this._collideWithWorld(this.cameraDirection);
  46312. }
  46313. else {
  46314. _super.prototype._updatePosition.call(this);
  46315. }
  46316. };
  46317. FreeCamera.prototype.dispose = function () {
  46318. this.inputs.clear();
  46319. _super.prototype.dispose.call(this);
  46320. };
  46321. FreeCamera.prototype.getClassName = function () {
  46322. return "FreeCamera";
  46323. };
  46324. __decorate([
  46325. BABYLON.serializeAsVector3()
  46326. ], FreeCamera.prototype, "ellipsoid", void 0);
  46327. __decorate([
  46328. BABYLON.serializeAsVector3()
  46329. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46330. __decorate([
  46331. BABYLON.serialize()
  46332. ], FreeCamera.prototype, "checkCollisions", void 0);
  46333. __decorate([
  46334. BABYLON.serialize()
  46335. ], FreeCamera.prototype, "applyGravity", void 0);
  46336. return FreeCamera;
  46337. }(BABYLON.TargetCamera));
  46338. BABYLON.FreeCamera = FreeCamera;
  46339. })(BABYLON || (BABYLON = {}));
  46340. //# sourceMappingURL=babylon.freeCamera.js.map
  46341. var BABYLON;
  46342. (function (BABYLON) {
  46343. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46344. function ArcRotateCameraKeyboardMoveInput() {
  46345. this._keys = new Array();
  46346. this.keysUp = [38];
  46347. this.keysDown = [40];
  46348. this.keysLeft = [37];
  46349. this.keysRight = [39];
  46350. this.keysReset = [220];
  46351. this.panningSensibility = 50.0;
  46352. this.zoomingSensibility = 25.0;
  46353. this.useAltToZoom = true;
  46354. }
  46355. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46356. var _this = this;
  46357. if (this._onCanvasBlurObserver) {
  46358. return;
  46359. }
  46360. this._scene = this.camera.getScene();
  46361. this._engine = this._scene.getEngine();
  46362. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46363. _this._keys = [];
  46364. });
  46365. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46366. var evt = info.event;
  46367. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46368. _this._ctrlPressed = evt.ctrlKey;
  46369. _this._altPressed = evt.altKey;
  46370. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46371. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46372. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46373. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46374. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46375. var index = _this._keys.indexOf(evt.keyCode);
  46376. if (index === -1) {
  46377. _this._keys.push(evt.keyCode);
  46378. }
  46379. if (evt.preventDefault) {
  46380. if (!noPreventDefault) {
  46381. evt.preventDefault();
  46382. }
  46383. }
  46384. }
  46385. }
  46386. else {
  46387. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46388. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46389. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46390. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46391. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46392. var index = _this._keys.indexOf(evt.keyCode);
  46393. if (index >= 0) {
  46394. _this._keys.splice(index, 1);
  46395. }
  46396. if (evt.preventDefault) {
  46397. if (!noPreventDefault) {
  46398. evt.preventDefault();
  46399. }
  46400. }
  46401. }
  46402. }
  46403. });
  46404. };
  46405. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46406. if (this._scene) {
  46407. if (this._onKeyboardObserver) {
  46408. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46409. }
  46410. if (this._onCanvasBlurObserver) {
  46411. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46412. }
  46413. this._onKeyboardObserver = null;
  46414. this._onCanvasBlurObserver = null;
  46415. }
  46416. this._keys = [];
  46417. };
  46418. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46419. if (this._onKeyboardObserver) {
  46420. var camera = this.camera;
  46421. for (var index = 0; index < this._keys.length; index++) {
  46422. var keyCode = this._keys[index];
  46423. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46424. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46425. camera.inertialPanningX -= 1 / this.panningSensibility;
  46426. }
  46427. else {
  46428. camera.inertialAlphaOffset -= 0.01;
  46429. }
  46430. }
  46431. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46432. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46433. camera.inertialPanningY += 1 / this.panningSensibility;
  46434. }
  46435. else if (this._altPressed && this.useAltToZoom) {
  46436. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46437. }
  46438. else {
  46439. camera.inertialBetaOffset -= 0.01;
  46440. }
  46441. }
  46442. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46443. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46444. camera.inertialPanningX += 1 / this.panningSensibility;
  46445. }
  46446. else {
  46447. camera.inertialAlphaOffset += 0.01;
  46448. }
  46449. }
  46450. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46451. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46452. camera.inertialPanningY -= 1 / this.panningSensibility;
  46453. }
  46454. else if (this._altPressed && this.useAltToZoom) {
  46455. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46456. }
  46457. else {
  46458. camera.inertialBetaOffset += 0.01;
  46459. }
  46460. }
  46461. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46462. camera.restoreState();
  46463. }
  46464. }
  46465. }
  46466. };
  46467. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46468. return "ArcRotateCameraKeyboardMoveInput";
  46469. };
  46470. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46471. return "keyboard";
  46472. };
  46473. __decorate([
  46474. BABYLON.serialize()
  46475. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46476. __decorate([
  46477. BABYLON.serialize()
  46478. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46479. __decorate([
  46480. BABYLON.serialize()
  46481. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46482. __decorate([
  46483. BABYLON.serialize()
  46484. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46485. __decorate([
  46486. BABYLON.serialize()
  46487. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46488. __decorate([
  46489. BABYLON.serialize()
  46490. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46491. __decorate([
  46492. BABYLON.serialize()
  46493. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46494. __decorate([
  46495. BABYLON.serialize()
  46496. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46497. return ArcRotateCameraKeyboardMoveInput;
  46498. }());
  46499. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46500. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46501. })(BABYLON || (BABYLON = {}));
  46502. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46503. var BABYLON;
  46504. (function (BABYLON) {
  46505. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46506. function ArcRotateCameraMouseWheelInput() {
  46507. this.wheelPrecision = 3.0;
  46508. /**
  46509. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46510. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46511. */
  46512. this.wheelDeltaPercentage = 0;
  46513. }
  46514. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46515. var _this = this;
  46516. this._wheel = function (p, s) {
  46517. //sanity check - this should be a PointerWheel event.
  46518. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46519. return;
  46520. var event = p.event;
  46521. var delta = 0;
  46522. if (event.wheelDelta) {
  46523. if (_this.wheelDeltaPercentage) {
  46524. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46525. if (event.wheelDelta > 0) {
  46526. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46527. }
  46528. else {
  46529. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46530. }
  46531. }
  46532. else {
  46533. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46534. }
  46535. }
  46536. else if (event.detail) {
  46537. delta = -event.detail / _this.wheelPrecision;
  46538. }
  46539. if (delta)
  46540. _this.camera.inertialRadiusOffset += delta;
  46541. if (event.preventDefault) {
  46542. if (!noPreventDefault) {
  46543. event.preventDefault();
  46544. }
  46545. }
  46546. };
  46547. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46548. };
  46549. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46550. if (this._observer && element) {
  46551. this.camera.getScene().onPointerObservable.remove(this._observer);
  46552. this._observer = null;
  46553. this._wheel = null;
  46554. }
  46555. };
  46556. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46557. return "ArcRotateCameraMouseWheelInput";
  46558. };
  46559. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46560. return "mousewheel";
  46561. };
  46562. __decorate([
  46563. BABYLON.serialize()
  46564. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46565. __decorate([
  46566. BABYLON.serialize()
  46567. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46568. return ArcRotateCameraMouseWheelInput;
  46569. }());
  46570. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46571. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46572. })(BABYLON || (BABYLON = {}));
  46573. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46574. var BABYLON;
  46575. (function (BABYLON) {
  46576. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46577. function ArcRotateCameraPointersInput() {
  46578. this.buttons = [0, 1, 2];
  46579. this.angularSensibilityX = 1000.0;
  46580. this.angularSensibilityY = 1000.0;
  46581. this.pinchPrecision = 12.0;
  46582. /**
  46583. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46584. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46585. */
  46586. this.pinchDeltaPercentage = 0;
  46587. this.panningSensibility = 1000.0;
  46588. this.multiTouchPanning = true;
  46589. this.multiTouchPanAndZoom = true;
  46590. this._isPanClick = false;
  46591. this.pinchInwards = true;
  46592. }
  46593. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46594. var _this = this;
  46595. var engine = this.camera.getEngine();
  46596. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46597. var pointA = null;
  46598. var pointB = null;
  46599. var previousPinchSquaredDistance = 0;
  46600. var initialDistance = 0;
  46601. var twoFingerActivityCount = 0;
  46602. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46603. this._pointerInput = function (p, s) {
  46604. var evt = p.event;
  46605. var isTouch = p.event.pointerType === "touch";
  46606. if (engine.isInVRExclusivePointerMode) {
  46607. return;
  46608. }
  46609. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46610. return;
  46611. }
  46612. var srcElement = (evt.srcElement || evt.target);
  46613. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46614. try {
  46615. srcElement.setPointerCapture(evt.pointerId);
  46616. }
  46617. catch (e) {
  46618. //Nothing to do with the error. Execution will continue.
  46619. }
  46620. // Manage panning with pan button click
  46621. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46622. // manage pointers
  46623. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46624. if (pointA === null) {
  46625. pointA = cacheSoloPointer;
  46626. }
  46627. else if (pointB === null) {
  46628. pointB = cacheSoloPointer;
  46629. }
  46630. if (!noPreventDefault) {
  46631. evt.preventDefault();
  46632. element.focus();
  46633. }
  46634. }
  46635. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46636. _this.camera.restoreState();
  46637. }
  46638. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46639. try {
  46640. srcElement.releasePointerCapture(evt.pointerId);
  46641. }
  46642. catch (e) {
  46643. //Nothing to do with the error.
  46644. }
  46645. cacheSoloPointer = null;
  46646. previousPinchSquaredDistance = 0;
  46647. previousMultiTouchPanPosition.isPaning = false;
  46648. previousMultiTouchPanPosition.isPinching = false;
  46649. twoFingerActivityCount = 0;
  46650. initialDistance = 0;
  46651. if (!isTouch) {
  46652. pointB = null; // Mouse and pen are mono pointer
  46653. }
  46654. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46655. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46656. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46657. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46658. if (engine._badOS) {
  46659. pointA = pointB = null;
  46660. }
  46661. else {
  46662. //only remove the impacted pointer in case of multitouch allowing on most
  46663. //platforms switching from rotate to zoom and pan seamlessly.
  46664. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46665. pointA = pointB;
  46666. pointB = null;
  46667. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46668. }
  46669. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46670. pointB = null;
  46671. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46672. }
  46673. else {
  46674. pointA = pointB = null;
  46675. }
  46676. }
  46677. if (!noPreventDefault) {
  46678. evt.preventDefault();
  46679. }
  46680. }
  46681. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46682. if (!noPreventDefault) {
  46683. evt.preventDefault();
  46684. }
  46685. // One button down
  46686. if (pointA && pointB === null && cacheSoloPointer) {
  46687. if (_this.panningSensibility !== 0 &&
  46688. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46689. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46690. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46691. }
  46692. else {
  46693. var offsetX = evt.clientX - cacheSoloPointer.x;
  46694. var offsetY = evt.clientY - cacheSoloPointer.y;
  46695. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46696. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46697. }
  46698. cacheSoloPointer.x = evt.clientX;
  46699. cacheSoloPointer.y = evt.clientY;
  46700. }
  46701. // Two buttons down: pinch/pan
  46702. else if (pointA && pointB) {
  46703. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46704. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46705. ed.x = evt.clientX;
  46706. ed.y = evt.clientY;
  46707. var direction = _this.pinchInwards ? 1 : -1;
  46708. var distX = pointA.x - pointB.x;
  46709. var distY = pointA.y - pointB.y;
  46710. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  46711. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  46712. if (previousPinchSquaredDistance === 0) {
  46713. initialDistance = pinchDistance;
  46714. previousPinchSquaredDistance = pinchSquaredDistance;
  46715. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  46716. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  46717. return;
  46718. }
  46719. if (_this.multiTouchPanAndZoom) {
  46720. if (_this.pinchDeltaPercentage) {
  46721. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46722. }
  46723. else {
  46724. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46725. (_this.pinchPrecision *
  46726. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46727. direction);
  46728. }
  46729. if (_this.panningSensibility !== 0) {
  46730. var pointersCenterX = (pointA.x + pointB.x) / 2;
  46731. var pointersCenterY = (pointA.y + pointB.y) / 2;
  46732. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  46733. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  46734. previousMultiTouchPanPosition.x = pointersCenterX;
  46735. previousMultiTouchPanPosition.y = pointersCenterY;
  46736. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  46737. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  46738. }
  46739. }
  46740. else {
  46741. twoFingerActivityCount++;
  46742. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  46743. if (_this.pinchDeltaPercentage) {
  46744. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46745. }
  46746. else {
  46747. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46748. (_this.pinchPrecision *
  46749. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46750. direction);
  46751. }
  46752. previousMultiTouchPanPosition.isPaning = false;
  46753. previousMultiTouchPanPosition.isPinching = true;
  46754. }
  46755. else {
  46756. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  46757. if (!previousMultiTouchPanPosition.isPaning) {
  46758. previousMultiTouchPanPosition.isPaning = true;
  46759. previousMultiTouchPanPosition.isPinching = false;
  46760. previousMultiTouchPanPosition.x = ed.x;
  46761. previousMultiTouchPanPosition.y = ed.y;
  46762. return;
  46763. }
  46764. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  46765. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  46766. }
  46767. }
  46768. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  46769. previousMultiTouchPanPosition.x = ed.x;
  46770. previousMultiTouchPanPosition.y = ed.y;
  46771. }
  46772. }
  46773. previousPinchSquaredDistance = pinchSquaredDistance;
  46774. }
  46775. }
  46776. };
  46777. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  46778. this._onContextMenu = function (evt) {
  46779. evt.preventDefault();
  46780. };
  46781. if (!this.camera._useCtrlForPanning) {
  46782. element.addEventListener("contextmenu", this._onContextMenu, false);
  46783. }
  46784. this._onLostFocus = function () {
  46785. //this._keys = [];
  46786. pointA = pointB = null;
  46787. previousPinchSquaredDistance = 0;
  46788. previousMultiTouchPanPosition.isPaning = false;
  46789. previousMultiTouchPanPosition.isPinching = false;
  46790. twoFingerActivityCount = 0;
  46791. cacheSoloPointer = null;
  46792. initialDistance = 0;
  46793. };
  46794. this._onMouseMove = function (evt) {
  46795. if (!engine.isPointerLock) {
  46796. return;
  46797. }
  46798. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46799. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46800. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46801. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46802. if (!noPreventDefault) {
  46803. evt.preventDefault();
  46804. }
  46805. };
  46806. this._onGestureStart = function (e) {
  46807. if (window.MSGesture === undefined) {
  46808. return;
  46809. }
  46810. if (!_this._MSGestureHandler) {
  46811. _this._MSGestureHandler = new MSGesture();
  46812. _this._MSGestureHandler.target = element;
  46813. }
  46814. _this._MSGestureHandler.addPointer(e.pointerId);
  46815. };
  46816. this._onGesture = function (e) {
  46817. _this.camera.radius *= e.scale;
  46818. if (e.preventDefault) {
  46819. if (!noPreventDefault) {
  46820. e.stopPropagation();
  46821. e.preventDefault();
  46822. }
  46823. }
  46824. };
  46825. element.addEventListener("mousemove", this._onMouseMove, false);
  46826. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  46827. element.addEventListener("MSGestureChange", this._onGesture, false);
  46828. BABYLON.Tools.RegisterTopRootEvents([
  46829. { name: "blur", handler: this._onLostFocus }
  46830. ]);
  46831. };
  46832. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  46833. if (this._onLostFocus) {
  46834. BABYLON.Tools.UnregisterTopRootEvents([
  46835. { name: "blur", handler: this._onLostFocus }
  46836. ]);
  46837. }
  46838. if (element && this._observer) {
  46839. this.camera.getScene().onPointerObservable.remove(this._observer);
  46840. this._observer = null;
  46841. if (this._onContextMenu) {
  46842. element.removeEventListener("contextmenu", this._onContextMenu);
  46843. }
  46844. if (this._onMouseMove) {
  46845. element.removeEventListener("mousemove", this._onMouseMove);
  46846. }
  46847. if (this._onGestureStart) {
  46848. element.removeEventListener("MSPointerDown", this._onGestureStart);
  46849. }
  46850. if (this._onGesture) {
  46851. element.removeEventListener("MSGestureChange", this._onGesture);
  46852. }
  46853. this._isPanClick = false;
  46854. this.pinchInwards = true;
  46855. this._onMouseMove = null;
  46856. this._onGestureStart = null;
  46857. this._onGesture = null;
  46858. this._MSGestureHandler = null;
  46859. this._onLostFocus = null;
  46860. this._onContextMenu = null;
  46861. }
  46862. };
  46863. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  46864. return "ArcRotateCameraPointersInput";
  46865. };
  46866. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  46867. return "pointers";
  46868. };
  46869. __decorate([
  46870. BABYLON.serialize()
  46871. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  46872. __decorate([
  46873. BABYLON.serialize()
  46874. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  46875. __decorate([
  46876. BABYLON.serialize()
  46877. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  46878. __decorate([
  46879. BABYLON.serialize()
  46880. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  46881. __decorate([
  46882. BABYLON.serialize()
  46883. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  46887. __decorate([
  46888. BABYLON.serialize()
  46889. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  46890. __decorate([
  46891. BABYLON.serialize()
  46892. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  46893. return ArcRotateCameraPointersInput;
  46894. }());
  46895. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  46896. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  46897. })(BABYLON || (BABYLON = {}));
  46898. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  46899. var BABYLON;
  46900. (function (BABYLON) {
  46901. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  46902. __extends(ArcRotateCameraInputsManager, _super);
  46903. function ArcRotateCameraInputsManager(camera) {
  46904. return _super.call(this, camera) || this;
  46905. }
  46906. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  46907. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  46908. return this;
  46909. };
  46910. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  46911. this.add(new BABYLON.ArcRotateCameraPointersInput());
  46912. return this;
  46913. };
  46914. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  46915. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  46916. return this;
  46917. };
  46918. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  46919. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  46920. return this;
  46921. };
  46922. return ArcRotateCameraInputsManager;
  46923. }(BABYLON.CameraInputsManager));
  46924. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  46925. })(BABYLON || (BABYLON = {}));
  46926. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  46927. var BABYLON;
  46928. (function (BABYLON) {
  46929. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  46930. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  46931. });
  46932. var ArcRotateCamera = /** @class */ (function (_super) {
  46933. __extends(ArcRotateCamera, _super);
  46934. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  46935. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46936. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  46937. _this.inertialAlphaOffset = 0;
  46938. _this.inertialBetaOffset = 0;
  46939. _this.inertialRadiusOffset = 0;
  46940. _this.lowerAlphaLimit = null;
  46941. _this.upperAlphaLimit = null;
  46942. _this.lowerBetaLimit = 0.01;
  46943. _this.upperBetaLimit = Math.PI;
  46944. _this.lowerRadiusLimit = null;
  46945. _this.upperRadiusLimit = null;
  46946. _this.inertialPanningX = 0;
  46947. _this.inertialPanningY = 0;
  46948. _this.pinchToPanMaxDistance = 20;
  46949. _this.panningDistanceLimit = null;
  46950. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  46951. _this.panningInertia = 0.9;
  46952. //-- end properties for backward compatibility for inputs
  46953. _this.zoomOnFactor = 1;
  46954. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  46955. _this.allowUpsideDown = true;
  46956. _this._viewMatrix = new BABYLON.Matrix();
  46957. // Panning
  46958. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  46959. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  46960. _this.checkCollisions = false;
  46961. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46962. _this._previousPosition = BABYLON.Vector3.Zero();
  46963. _this._collisionVelocity = BABYLON.Vector3.Zero();
  46964. _this._newPosition = BABYLON.Vector3.Zero();
  46965. _this._computationVector = BABYLON.Vector3.Zero();
  46966. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46967. if (collidedMesh === void 0) { collidedMesh = null; }
  46968. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  46969. newPosition.multiplyInPlace(_this._collider._radius);
  46970. }
  46971. if (!collidedMesh) {
  46972. _this._previousPosition.copyFrom(_this.position);
  46973. }
  46974. else {
  46975. _this.setPosition(newPosition);
  46976. if (_this.onCollide) {
  46977. _this.onCollide(collidedMesh);
  46978. }
  46979. }
  46980. // Recompute because of constraints
  46981. var cosa = Math.cos(_this.alpha);
  46982. var sina = Math.sin(_this.alpha);
  46983. var cosb = Math.cos(_this.beta);
  46984. var sinb = Math.sin(_this.beta);
  46985. if (sinb === 0) {
  46986. sinb = 0.0001;
  46987. }
  46988. var target = _this._getTargetPosition();
  46989. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  46990. target.addToRef(_this._computationVector, _this._newPosition);
  46991. _this.position.copyFrom(_this._newPosition);
  46992. var up = _this.upVector;
  46993. if (_this.allowUpsideDown && _this.beta < 0) {
  46994. up = up.clone();
  46995. up = up.negate();
  46996. }
  46997. _this._computeViewMatrix(_this.position, target, up);
  46998. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  46999. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47000. _this._collisionTriggered = false;
  47001. };
  47002. _this._target = BABYLON.Vector3.Zero();
  47003. if (target) {
  47004. _this.setTarget(target);
  47005. }
  47006. _this.alpha = alpha;
  47007. _this.beta = beta;
  47008. _this.radius = radius;
  47009. _this.getViewMatrix();
  47010. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47011. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47012. return _this;
  47013. }
  47014. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47015. get: function () {
  47016. return this._target;
  47017. },
  47018. set: function (value) {
  47019. this.setTarget(value);
  47020. },
  47021. enumerable: true,
  47022. configurable: true
  47023. });
  47024. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47025. //-- begin properties for backward compatibility for inputs
  47026. get: function () {
  47027. var pointers = this.inputs.attached["pointers"];
  47028. if (pointers)
  47029. return pointers.angularSensibilityX;
  47030. return 0;
  47031. },
  47032. set: function (value) {
  47033. var pointers = this.inputs.attached["pointers"];
  47034. if (pointers) {
  47035. pointers.angularSensibilityX = value;
  47036. }
  47037. },
  47038. enumerable: true,
  47039. configurable: true
  47040. });
  47041. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47042. get: function () {
  47043. var pointers = this.inputs.attached["pointers"];
  47044. if (pointers)
  47045. return pointers.angularSensibilityY;
  47046. return 0;
  47047. },
  47048. set: function (value) {
  47049. var pointers = this.inputs.attached["pointers"];
  47050. if (pointers) {
  47051. pointers.angularSensibilityY = value;
  47052. }
  47053. },
  47054. enumerable: true,
  47055. configurable: true
  47056. });
  47057. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47058. get: function () {
  47059. var pointers = this.inputs.attached["pointers"];
  47060. if (pointers)
  47061. return pointers.pinchPrecision;
  47062. return 0;
  47063. },
  47064. set: function (value) {
  47065. var pointers = this.inputs.attached["pointers"];
  47066. if (pointers) {
  47067. pointers.pinchPrecision = value;
  47068. }
  47069. },
  47070. enumerable: true,
  47071. configurable: true
  47072. });
  47073. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47074. get: function () {
  47075. var pointers = this.inputs.attached["pointers"];
  47076. if (pointers)
  47077. return pointers.pinchDeltaPercentage;
  47078. return 0;
  47079. },
  47080. set: function (value) {
  47081. var pointers = this.inputs.attached["pointers"];
  47082. if (pointers) {
  47083. pointers.pinchDeltaPercentage = value;
  47084. }
  47085. },
  47086. enumerable: true,
  47087. configurable: true
  47088. });
  47089. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47090. get: function () {
  47091. var pointers = this.inputs.attached["pointers"];
  47092. if (pointers)
  47093. return pointers.panningSensibility;
  47094. return 0;
  47095. },
  47096. set: function (value) {
  47097. var pointers = this.inputs.attached["pointers"];
  47098. if (pointers) {
  47099. pointers.panningSensibility = value;
  47100. }
  47101. },
  47102. enumerable: true,
  47103. configurable: true
  47104. });
  47105. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47106. get: function () {
  47107. var keyboard = this.inputs.attached["keyboard"];
  47108. if (keyboard)
  47109. return keyboard.keysUp;
  47110. return [];
  47111. },
  47112. set: function (value) {
  47113. var keyboard = this.inputs.attached["keyboard"];
  47114. if (keyboard)
  47115. keyboard.keysUp = value;
  47116. },
  47117. enumerable: true,
  47118. configurable: true
  47119. });
  47120. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47121. get: function () {
  47122. var keyboard = this.inputs.attached["keyboard"];
  47123. if (keyboard)
  47124. return keyboard.keysDown;
  47125. return [];
  47126. },
  47127. set: function (value) {
  47128. var keyboard = this.inputs.attached["keyboard"];
  47129. if (keyboard)
  47130. keyboard.keysDown = value;
  47131. },
  47132. enumerable: true,
  47133. configurable: true
  47134. });
  47135. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47136. get: function () {
  47137. var keyboard = this.inputs.attached["keyboard"];
  47138. if (keyboard)
  47139. return keyboard.keysLeft;
  47140. return [];
  47141. },
  47142. set: function (value) {
  47143. var keyboard = this.inputs.attached["keyboard"];
  47144. if (keyboard)
  47145. keyboard.keysLeft = value;
  47146. },
  47147. enumerable: true,
  47148. configurable: true
  47149. });
  47150. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47151. get: function () {
  47152. var keyboard = this.inputs.attached["keyboard"];
  47153. if (keyboard)
  47154. return keyboard.keysRight;
  47155. return [];
  47156. },
  47157. set: function (value) {
  47158. var keyboard = this.inputs.attached["keyboard"];
  47159. if (keyboard)
  47160. keyboard.keysRight = value;
  47161. },
  47162. enumerable: true,
  47163. configurable: true
  47164. });
  47165. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47166. get: function () {
  47167. var mousewheel = this.inputs.attached["mousewheel"];
  47168. if (mousewheel)
  47169. return mousewheel.wheelPrecision;
  47170. return 0;
  47171. },
  47172. set: function (value) {
  47173. var mousewheel = this.inputs.attached["mousewheel"];
  47174. if (mousewheel)
  47175. mousewheel.wheelPrecision = value;
  47176. },
  47177. enumerable: true,
  47178. configurable: true
  47179. });
  47180. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47181. get: function () {
  47182. var mousewheel = this.inputs.attached["mousewheel"];
  47183. if (mousewheel)
  47184. return mousewheel.wheelDeltaPercentage;
  47185. return 0;
  47186. },
  47187. set: function (value) {
  47188. var mousewheel = this.inputs.attached["mousewheel"];
  47189. if (mousewheel)
  47190. mousewheel.wheelDeltaPercentage = value;
  47191. },
  47192. enumerable: true,
  47193. configurable: true
  47194. });
  47195. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47196. get: function () {
  47197. return this._bouncingBehavior;
  47198. },
  47199. enumerable: true,
  47200. configurable: true
  47201. });
  47202. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47203. get: function () {
  47204. return this._bouncingBehavior != null;
  47205. },
  47206. set: function (value) {
  47207. if (value === this.useBouncingBehavior) {
  47208. return;
  47209. }
  47210. if (value) {
  47211. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47212. this.addBehavior(this._bouncingBehavior);
  47213. }
  47214. else if (this._bouncingBehavior) {
  47215. this.removeBehavior(this._bouncingBehavior);
  47216. this._bouncingBehavior = null;
  47217. }
  47218. },
  47219. enumerable: true,
  47220. configurable: true
  47221. });
  47222. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47223. get: function () {
  47224. return this._framingBehavior;
  47225. },
  47226. enumerable: true,
  47227. configurable: true
  47228. });
  47229. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47230. get: function () {
  47231. return this._framingBehavior != null;
  47232. },
  47233. set: function (value) {
  47234. if (value === this.useFramingBehavior) {
  47235. return;
  47236. }
  47237. if (value) {
  47238. this._framingBehavior = new BABYLON.FramingBehavior();
  47239. this.addBehavior(this._framingBehavior);
  47240. }
  47241. else if (this._framingBehavior) {
  47242. this.removeBehavior(this._framingBehavior);
  47243. this._framingBehavior = null;
  47244. }
  47245. },
  47246. enumerable: true,
  47247. configurable: true
  47248. });
  47249. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47250. get: function () {
  47251. return this._autoRotationBehavior;
  47252. },
  47253. enumerable: true,
  47254. configurable: true
  47255. });
  47256. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47257. get: function () {
  47258. return this._autoRotationBehavior != null;
  47259. },
  47260. set: function (value) {
  47261. if (value === this.useAutoRotationBehavior) {
  47262. return;
  47263. }
  47264. if (value) {
  47265. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47266. this.addBehavior(this._autoRotationBehavior);
  47267. }
  47268. else if (this._autoRotationBehavior) {
  47269. this.removeBehavior(this._autoRotationBehavior);
  47270. this._autoRotationBehavior = null;
  47271. }
  47272. },
  47273. enumerable: true,
  47274. configurable: true
  47275. });
  47276. // Cache
  47277. ArcRotateCamera.prototype._initCache = function () {
  47278. _super.prototype._initCache.call(this);
  47279. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47280. this._cache.alpha = undefined;
  47281. this._cache.beta = undefined;
  47282. this._cache.radius = undefined;
  47283. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47284. };
  47285. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47286. if (!ignoreParentClass) {
  47287. _super.prototype._updateCache.call(this);
  47288. }
  47289. this._cache._target.copyFrom(this._getTargetPosition());
  47290. this._cache.alpha = this.alpha;
  47291. this._cache.beta = this.beta;
  47292. this._cache.radius = this.radius;
  47293. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47294. };
  47295. ArcRotateCamera.prototype._getTargetPosition = function () {
  47296. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47297. var pos = this._targetHost.getAbsolutePosition();
  47298. if (this._targetBoundingCenter) {
  47299. pos.addToRef(this._targetBoundingCenter, this._target);
  47300. }
  47301. else {
  47302. this._target.copyFrom(pos);
  47303. }
  47304. }
  47305. var lockedTargetPosition = this._getLockedTargetPosition();
  47306. if (lockedTargetPosition) {
  47307. return lockedTargetPosition;
  47308. }
  47309. return this._target;
  47310. };
  47311. ArcRotateCamera.prototype.storeState = function () {
  47312. this._storedAlpha = this.alpha;
  47313. this._storedBeta = this.beta;
  47314. this._storedRadius = this.radius;
  47315. this._storedTarget = this._getTargetPosition().clone();
  47316. return _super.prototype.storeState.call(this);
  47317. };
  47318. /**
  47319. * Restored camera state. You must call storeState() first
  47320. */
  47321. ArcRotateCamera.prototype._restoreStateValues = function () {
  47322. if (!_super.prototype._restoreStateValues.call(this)) {
  47323. return false;
  47324. }
  47325. this.alpha = this._storedAlpha;
  47326. this.beta = this._storedBeta;
  47327. this.radius = this._storedRadius;
  47328. this.setTarget(this._storedTarget.clone());
  47329. this.inertialAlphaOffset = 0;
  47330. this.inertialBetaOffset = 0;
  47331. this.inertialRadiusOffset = 0;
  47332. this.inertialPanningX = 0;
  47333. this.inertialPanningY = 0;
  47334. return true;
  47335. };
  47336. // Synchronized
  47337. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47338. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47339. return false;
  47340. return this._cache._target.equals(this._getTargetPosition())
  47341. && this._cache.alpha === this.alpha
  47342. && this._cache.beta === this.beta
  47343. && this._cache.radius === this.radius
  47344. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47345. };
  47346. // Methods
  47347. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47348. var _this = this;
  47349. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47350. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47351. this._useCtrlForPanning = useCtrlForPanning;
  47352. this._panningMouseButton = panningMouseButton;
  47353. this.inputs.attachElement(element, noPreventDefault);
  47354. this._reset = function () {
  47355. _this.inertialAlphaOffset = 0;
  47356. _this.inertialBetaOffset = 0;
  47357. _this.inertialRadiusOffset = 0;
  47358. _this.inertialPanningX = 0;
  47359. _this.inertialPanningY = 0;
  47360. };
  47361. };
  47362. ArcRotateCamera.prototype.detachControl = function (element) {
  47363. this.inputs.detachElement(element);
  47364. if (this._reset) {
  47365. this._reset();
  47366. }
  47367. };
  47368. ArcRotateCamera.prototype._checkInputs = function () {
  47369. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47370. if (this._collisionTriggered) {
  47371. return;
  47372. }
  47373. this.inputs.checkInputs();
  47374. // Inertia
  47375. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47376. var inertialAlphaOffset = this.inertialAlphaOffset;
  47377. if (this.beta <= 0)
  47378. inertialAlphaOffset *= -1;
  47379. if (this.getScene().useRightHandedSystem)
  47380. inertialAlphaOffset *= -1;
  47381. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47382. inertialAlphaOffset *= -1;
  47383. this.alpha += inertialAlphaOffset;
  47384. this.beta += this.inertialBetaOffset;
  47385. this.radius -= this.inertialRadiusOffset;
  47386. this.inertialAlphaOffset *= this.inertia;
  47387. this.inertialBetaOffset *= this.inertia;
  47388. this.inertialRadiusOffset *= this.inertia;
  47389. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47390. this.inertialAlphaOffset = 0;
  47391. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47392. this.inertialBetaOffset = 0;
  47393. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47394. this.inertialRadiusOffset = 0;
  47395. }
  47396. // Panning inertia
  47397. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47398. if (!this._localDirection) {
  47399. this._localDirection = BABYLON.Vector3.Zero();
  47400. this._transformedDirection = BABYLON.Vector3.Zero();
  47401. }
  47402. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47403. this._localDirection.multiplyInPlace(this.panningAxis);
  47404. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47405. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47406. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47407. if (!this.panningAxis.y) {
  47408. this._transformedDirection.y = 0;
  47409. }
  47410. if (!this._targetHost) {
  47411. if (this.panningDistanceLimit) {
  47412. this._transformedDirection.addInPlace(this._target);
  47413. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47414. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47415. this._target.copyFrom(this._transformedDirection);
  47416. }
  47417. }
  47418. else {
  47419. this._target.addInPlace(this._transformedDirection);
  47420. }
  47421. }
  47422. this.inertialPanningX *= this.panningInertia;
  47423. this.inertialPanningY *= this.panningInertia;
  47424. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47425. this.inertialPanningX = 0;
  47426. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47427. this.inertialPanningY = 0;
  47428. }
  47429. // Limits
  47430. this._checkLimits();
  47431. _super.prototype._checkInputs.call(this);
  47432. };
  47433. ArcRotateCamera.prototype._checkLimits = function () {
  47434. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47435. if (this.allowUpsideDown && this.beta > Math.PI) {
  47436. this.beta = this.beta - (2 * Math.PI);
  47437. }
  47438. }
  47439. else {
  47440. if (this.beta < this.lowerBetaLimit) {
  47441. this.beta = this.lowerBetaLimit;
  47442. }
  47443. }
  47444. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47445. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47446. this.beta = this.beta + (2 * Math.PI);
  47447. }
  47448. }
  47449. else {
  47450. if (this.beta > this.upperBetaLimit) {
  47451. this.beta = this.upperBetaLimit;
  47452. }
  47453. }
  47454. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47455. this.alpha = this.lowerAlphaLimit;
  47456. }
  47457. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47458. this.alpha = this.upperAlphaLimit;
  47459. }
  47460. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47461. this.radius = this.lowerRadiusLimit;
  47462. }
  47463. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47464. this.radius = this.upperRadiusLimit;
  47465. }
  47466. };
  47467. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47468. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47469. this.radius = this._computationVector.length();
  47470. if (this.radius === 0) {
  47471. this.radius = 0.0001; // Just to avoid division by zero
  47472. }
  47473. // Alpha
  47474. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47475. if (this._computationVector.z < 0) {
  47476. this.alpha = 2 * Math.PI - this.alpha;
  47477. }
  47478. // Beta
  47479. this.beta = Math.acos(this._computationVector.y / this.radius);
  47480. this._checkLimits();
  47481. };
  47482. ArcRotateCamera.prototype.setPosition = function (position) {
  47483. if (this.position.equals(position)) {
  47484. return;
  47485. }
  47486. this.position.copyFrom(position);
  47487. this.rebuildAnglesAndRadius();
  47488. };
  47489. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47490. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47491. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47492. if (target.getBoundingInfo) {
  47493. if (toBoundingCenter) {
  47494. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47495. }
  47496. else {
  47497. this._targetBoundingCenter = null;
  47498. }
  47499. this._targetHost = target;
  47500. this._target = this._getTargetPosition();
  47501. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47502. }
  47503. else {
  47504. var newTarget = target;
  47505. var currentTarget = this._getTargetPosition();
  47506. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47507. return;
  47508. }
  47509. this._targetHost = null;
  47510. this._target = newTarget;
  47511. this._targetBoundingCenter = null;
  47512. this.onMeshTargetChangedObservable.notifyObservers(null);
  47513. }
  47514. this.rebuildAnglesAndRadius();
  47515. };
  47516. ArcRotateCamera.prototype._getViewMatrix = function () {
  47517. // Compute
  47518. var cosa = Math.cos(this.alpha);
  47519. var sina = Math.sin(this.alpha);
  47520. var cosb = Math.cos(this.beta);
  47521. var sinb = Math.sin(this.beta);
  47522. if (sinb === 0) {
  47523. sinb = 0.0001;
  47524. }
  47525. var target = this._getTargetPosition();
  47526. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47527. target.addToRef(this._computationVector, this._newPosition);
  47528. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47529. if (!this._collider) {
  47530. this._collider = new BABYLON.Collider();
  47531. }
  47532. this._collider._radius = this.collisionRadius;
  47533. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47534. this._collisionTriggered = true;
  47535. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47536. }
  47537. else {
  47538. this.position.copyFrom(this._newPosition);
  47539. var up = this.upVector;
  47540. if (this.allowUpsideDown && sinb < 0) {
  47541. up = up.clone();
  47542. up = up.negate();
  47543. }
  47544. this._computeViewMatrix(this.position, target, up);
  47545. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47546. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47547. }
  47548. this._currentTarget = target;
  47549. return this._viewMatrix;
  47550. };
  47551. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47552. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47553. meshes = meshes || this.getScene().meshes;
  47554. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47555. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47556. this.radius = distance * this.zoomOnFactor;
  47557. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47558. };
  47559. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47560. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47561. var meshesOrMinMaxVector;
  47562. var distance;
  47563. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47564. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47565. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47566. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47567. }
  47568. else { //minMaxVector and distance
  47569. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47570. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47571. distance = minMaxVectorAndDistance.distance;
  47572. }
  47573. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47574. if (!doNotUpdateMaxZ) {
  47575. this.maxZ = distance * 2;
  47576. }
  47577. };
  47578. /**
  47579. * @override
  47580. * Override Camera.createRigCamera
  47581. */
  47582. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47583. var alphaShift = 0;
  47584. switch (this.cameraRigMode) {
  47585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47586. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47587. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47588. case BABYLON.Camera.RIG_MODE_VR:
  47589. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47590. break;
  47591. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47592. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47593. break;
  47594. }
  47595. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47596. rigCam._cameraRigParams = {};
  47597. return rigCam;
  47598. };
  47599. /**
  47600. * @override
  47601. * Override Camera._updateRigCameras
  47602. */
  47603. ArcRotateCamera.prototype._updateRigCameras = function () {
  47604. var camLeft = this._rigCameras[0];
  47605. var camRight = this._rigCameras[1];
  47606. camLeft.beta = camRight.beta = this.beta;
  47607. camLeft.radius = camRight.radius = this.radius;
  47608. switch (this.cameraRigMode) {
  47609. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47610. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47611. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47612. case BABYLON.Camera.RIG_MODE_VR:
  47613. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47614. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47615. break;
  47616. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47617. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47618. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47619. break;
  47620. }
  47621. _super.prototype._updateRigCameras.call(this);
  47622. };
  47623. ArcRotateCamera.prototype.dispose = function () {
  47624. this.inputs.clear();
  47625. _super.prototype.dispose.call(this);
  47626. };
  47627. ArcRotateCamera.prototype.getClassName = function () {
  47628. return "ArcRotateCamera";
  47629. };
  47630. __decorate([
  47631. BABYLON.serialize()
  47632. ], ArcRotateCamera.prototype, "alpha", void 0);
  47633. __decorate([
  47634. BABYLON.serialize()
  47635. ], ArcRotateCamera.prototype, "beta", void 0);
  47636. __decorate([
  47637. BABYLON.serialize()
  47638. ], ArcRotateCamera.prototype, "radius", void 0);
  47639. __decorate([
  47640. BABYLON.serializeAsVector3("target")
  47641. ], ArcRotateCamera.prototype, "_target", void 0);
  47642. __decorate([
  47643. BABYLON.serialize()
  47644. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47645. __decorate([
  47646. BABYLON.serialize()
  47647. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47648. __decorate([
  47649. BABYLON.serialize()
  47650. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47651. __decorate([
  47652. BABYLON.serialize()
  47653. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47654. __decorate([
  47655. BABYLON.serialize()
  47656. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47657. __decorate([
  47658. BABYLON.serialize()
  47659. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47660. __decorate([
  47661. BABYLON.serialize()
  47662. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47663. __decorate([
  47664. BABYLON.serialize()
  47665. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47666. __decorate([
  47667. BABYLON.serialize()
  47668. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47669. __decorate([
  47670. BABYLON.serialize()
  47671. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47672. __decorate([
  47673. BABYLON.serialize()
  47674. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47675. __decorate([
  47676. BABYLON.serialize()
  47677. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47678. __decorate([
  47679. BABYLON.serialize()
  47680. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47681. __decorate([
  47682. BABYLON.serializeAsVector3()
  47683. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47684. __decorate([
  47685. BABYLON.serialize()
  47686. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47687. __decorate([
  47688. BABYLON.serialize()
  47689. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47690. __decorate([
  47691. BABYLON.serialize()
  47692. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47693. return ArcRotateCamera;
  47694. }(BABYLON.TargetCamera));
  47695. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47696. })(BABYLON || (BABYLON = {}));
  47697. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47698. var BABYLON;
  47699. (function (BABYLON) {
  47700. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  47701. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  47702. });
  47703. /**
  47704. * The HemisphericLight simulates the ambient environment light,
  47705. * so the passed direction is the light reflection direction, not the incoming direction.
  47706. */
  47707. var HemisphericLight = /** @class */ (function (_super) {
  47708. __extends(HemisphericLight, _super);
  47709. /**
  47710. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  47711. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  47712. * The HemisphericLight can't cast shadows.
  47713. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47714. * @param name The friendly name of the light
  47715. * @param direction The direction of the light reflection
  47716. * @param scene The scene the light belongs to
  47717. */
  47718. function HemisphericLight(name, direction, scene) {
  47719. var _this = _super.call(this, name, scene) || this;
  47720. /**
  47721. * The groundColor is the light in the opposite direction to the one specified during creation.
  47722. * 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.
  47723. */
  47724. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  47725. _this.direction = direction || BABYLON.Vector3.Up();
  47726. return _this;
  47727. }
  47728. HemisphericLight.prototype._buildUniformLayout = function () {
  47729. this._uniformBuffer.addUniform("vLightData", 4);
  47730. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47731. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47732. this._uniformBuffer.addUniform("vLightGround", 3);
  47733. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47734. this._uniformBuffer.addUniform("depthValues", 2);
  47735. this._uniformBuffer.create();
  47736. };
  47737. /**
  47738. * Returns the string "HemisphericLight".
  47739. * @return The class name
  47740. */
  47741. HemisphericLight.prototype.getClassName = function () {
  47742. return "HemisphericLight";
  47743. };
  47744. /**
  47745. * Sets the HemisphericLight direction towards the passed target (Vector3).
  47746. * Returns the updated direction.
  47747. * @param target The target the direction should point to
  47748. * @return The computed direction
  47749. */
  47750. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  47751. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  47752. return this.direction;
  47753. };
  47754. /**
  47755. * Returns the shadow generator associated to the light.
  47756. * @returns Always null for hemispheric lights because it does not support shadows.
  47757. */
  47758. HemisphericLight.prototype.getShadowGenerator = function () {
  47759. return null;
  47760. };
  47761. /**
  47762. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  47763. * @param effect The effect to update
  47764. * @param lightIndex The index of the light in the effect to update
  47765. * @returns The hemispheric light
  47766. */
  47767. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  47768. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47769. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  47770. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  47771. return this;
  47772. };
  47773. /**
  47774. * @hidden internal use only.
  47775. */
  47776. HemisphericLight.prototype._getWorldMatrix = function () {
  47777. if (!this._worldMatrix) {
  47778. this._worldMatrix = BABYLON.Matrix.Identity();
  47779. }
  47780. return this._worldMatrix;
  47781. };
  47782. /**
  47783. * Returns the integer 3.
  47784. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47785. */
  47786. HemisphericLight.prototype.getTypeID = function () {
  47787. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  47788. };
  47789. /**
  47790. * Prepares the list of defines specific to the light type.
  47791. * @param defines the list of defines
  47792. * @param lightIndex defines the index of the light for the effect
  47793. */
  47794. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  47795. defines["HEMILIGHT" + lightIndex] = true;
  47796. };
  47797. __decorate([
  47798. BABYLON.serializeAsColor3()
  47799. ], HemisphericLight.prototype, "groundColor", void 0);
  47800. __decorate([
  47801. BABYLON.serializeAsVector3()
  47802. ], HemisphericLight.prototype, "direction", void 0);
  47803. return HemisphericLight;
  47804. }(BABYLON.Light));
  47805. BABYLON.HemisphericLight = HemisphericLight;
  47806. })(BABYLON || (BABYLON = {}));
  47807. //# sourceMappingURL=babylon.hemisphericLight.js.map
  47808. var BABYLON;
  47809. (function (BABYLON) {
  47810. /**
  47811. * Base implementation IShadowLight
  47812. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  47813. */
  47814. var ShadowLight = /** @class */ (function (_super) {
  47815. __extends(ShadowLight, _super);
  47816. function ShadowLight() {
  47817. var _this = _super !== null && _super.apply(this, arguments) || this;
  47818. _this._needProjectionMatrixCompute = true;
  47819. return _this;
  47820. }
  47821. ShadowLight.prototype._setPosition = function (value) {
  47822. this._position = value;
  47823. };
  47824. Object.defineProperty(ShadowLight.prototype, "position", {
  47825. /**
  47826. * Sets the position the shadow will be casted from. Also use as the light position for both
  47827. * point and spot lights.
  47828. */
  47829. get: function () {
  47830. return this._position;
  47831. },
  47832. /**
  47833. * Sets the position the shadow will be casted from. Also use as the light position for both
  47834. * point and spot lights.
  47835. */
  47836. set: function (value) {
  47837. this._setPosition(value);
  47838. },
  47839. enumerable: true,
  47840. configurable: true
  47841. });
  47842. ShadowLight.prototype._setDirection = function (value) {
  47843. this._direction = value;
  47844. };
  47845. Object.defineProperty(ShadowLight.prototype, "direction", {
  47846. /**
  47847. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  47848. * Also use as the light direction on spot and directional lights.
  47849. */
  47850. get: function () {
  47851. return this._direction;
  47852. },
  47853. /**
  47854. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  47855. * Also use as the light direction on spot and directional lights.
  47856. */
  47857. set: function (value) {
  47858. this._setDirection(value);
  47859. },
  47860. enumerable: true,
  47861. configurable: true
  47862. });
  47863. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  47864. /**
  47865. * Gets the shadow projection clipping minimum z value.
  47866. */
  47867. get: function () {
  47868. return this._shadowMinZ;
  47869. },
  47870. /**
  47871. * Sets the shadow projection clipping minimum z value.
  47872. */
  47873. set: function (value) {
  47874. this._shadowMinZ = value;
  47875. this.forceProjectionMatrixCompute();
  47876. },
  47877. enumerable: true,
  47878. configurable: true
  47879. });
  47880. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  47881. /**
  47882. * Sets the shadow projection clipping maximum z value.
  47883. */
  47884. get: function () {
  47885. return this._shadowMaxZ;
  47886. },
  47887. /**
  47888. * Gets the shadow projection clipping maximum z value.
  47889. */
  47890. set: function (value) {
  47891. this._shadowMaxZ = value;
  47892. this.forceProjectionMatrixCompute();
  47893. },
  47894. enumerable: true,
  47895. configurable: true
  47896. });
  47897. /**
  47898. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  47899. * @returns true if the information has been computed, false if it does not need to (no parenting)
  47900. */
  47901. ShadowLight.prototype.computeTransformedInformation = function () {
  47902. if (this.parent && this.parent.getWorldMatrix) {
  47903. if (!this.transformedPosition) {
  47904. this.transformedPosition = BABYLON.Vector3.Zero();
  47905. }
  47906. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  47907. // In case the direction is present.
  47908. if (this.direction) {
  47909. if (!this.transformedDirection) {
  47910. this.transformedDirection = BABYLON.Vector3.Zero();
  47911. }
  47912. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  47913. }
  47914. return true;
  47915. }
  47916. return false;
  47917. };
  47918. /**
  47919. * Return the depth scale used for the shadow map.
  47920. * @returns the depth scale.
  47921. */
  47922. ShadowLight.prototype.getDepthScale = function () {
  47923. return 50.0;
  47924. };
  47925. /**
  47926. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  47927. * @param faceIndex The index of the face we are computed the direction to generate shadow
  47928. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  47929. */
  47930. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  47931. return this.transformedDirection ? this.transformedDirection : this.direction;
  47932. };
  47933. /**
  47934. * Returns the ShadowLight absolute position in the World.
  47935. * @returns the position vector in world space
  47936. */
  47937. ShadowLight.prototype.getAbsolutePosition = function () {
  47938. return this.transformedPosition ? this.transformedPosition : this.position;
  47939. };
  47940. /**
  47941. * Sets the ShadowLight direction toward the passed target.
  47942. * @param target The point tot target in local space
  47943. * @returns the updated ShadowLight direction
  47944. */
  47945. ShadowLight.prototype.setDirectionToTarget = function (target) {
  47946. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  47947. return this.direction;
  47948. };
  47949. /**
  47950. * Returns the light rotation in euler definition.
  47951. * @returns the x y z rotation in local space.
  47952. */
  47953. ShadowLight.prototype.getRotation = function () {
  47954. this.direction.normalize();
  47955. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  47956. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  47957. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  47958. };
  47959. /**
  47960. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  47961. * @returns true if a cube texture needs to be use
  47962. */
  47963. ShadowLight.prototype.needCube = function () {
  47964. return false;
  47965. };
  47966. /**
  47967. * Detects if the projection matrix requires to be recomputed this frame.
  47968. * @returns true if it requires to be recomputed otherwise, false.
  47969. */
  47970. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  47971. return this._needProjectionMatrixCompute;
  47972. };
  47973. /**
  47974. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  47975. */
  47976. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  47977. this._needProjectionMatrixCompute = true;
  47978. };
  47979. /**
  47980. * Get the world matrix of the sahdow lights.
  47981. * @hidden Internal Use Only
  47982. */
  47983. ShadowLight.prototype._getWorldMatrix = function () {
  47984. if (!this._worldMatrix) {
  47985. this._worldMatrix = BABYLON.Matrix.Identity();
  47986. }
  47987. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  47988. return this._worldMatrix;
  47989. };
  47990. /**
  47991. * Gets the minZ used for shadow according to both the scene and the light.
  47992. * @param activeCamera The camera we are returning the min for
  47993. * @returns the depth min z
  47994. */
  47995. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  47996. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  47997. };
  47998. /**
  47999. * Gets the maxZ used for shadow according to both the scene and the light.
  48000. * @param activeCamera The camera we are returning the max for
  48001. * @returns the depth max z
  48002. */
  48003. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48004. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48005. };
  48006. /**
  48007. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48008. * @param matrix The materix to updated with the projection information
  48009. * @param viewMatrix The transform matrix of the light
  48010. * @param renderList The list of mesh to render in the map
  48011. * @returns The current light
  48012. */
  48013. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48014. if (this.customProjectionMatrixBuilder) {
  48015. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48016. }
  48017. else {
  48018. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48019. }
  48020. return this;
  48021. };
  48022. __decorate([
  48023. BABYLON.serializeAsVector3()
  48024. ], ShadowLight.prototype, "position", null);
  48025. __decorate([
  48026. BABYLON.serializeAsVector3()
  48027. ], ShadowLight.prototype, "direction", null);
  48028. __decorate([
  48029. BABYLON.serialize()
  48030. ], ShadowLight.prototype, "shadowMinZ", null);
  48031. __decorate([
  48032. BABYLON.serialize()
  48033. ], ShadowLight.prototype, "shadowMaxZ", null);
  48034. return ShadowLight;
  48035. }(BABYLON.Light));
  48036. BABYLON.ShadowLight = ShadowLight;
  48037. })(BABYLON || (BABYLON = {}));
  48038. //# sourceMappingURL=babylon.shadowLight.js.map
  48039. var BABYLON;
  48040. (function (BABYLON) {
  48041. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48042. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48043. });
  48044. /**
  48045. * A point light is a light defined by an unique point in world space.
  48046. * The light is emitted in every direction from this point.
  48047. * A good example of a point light is a standard light bulb.
  48048. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48049. */
  48050. var PointLight = /** @class */ (function (_super) {
  48051. __extends(PointLight, _super);
  48052. /**
  48053. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48054. * A PointLight emits the light in every direction.
  48055. * It can cast shadows.
  48056. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48057. * ```javascript
  48058. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48059. * ```
  48060. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48061. * @param name The light friendly name
  48062. * @param position The position of the point light in the scene
  48063. * @param scene The scene the lights belongs to
  48064. */
  48065. function PointLight(name, position, scene) {
  48066. var _this = _super.call(this, name, scene) || this;
  48067. _this._shadowAngle = Math.PI / 2;
  48068. _this.position = position;
  48069. return _this;
  48070. }
  48071. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48072. /**
  48073. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48074. * This specifies what angle the shadow will use to be created.
  48075. *
  48076. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48077. */
  48078. get: function () {
  48079. return this._shadowAngle;
  48080. },
  48081. /**
  48082. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48083. * This specifies what angle the shadow will use to be created.
  48084. *
  48085. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48086. */
  48087. set: function (value) {
  48088. this._shadowAngle = value;
  48089. this.forceProjectionMatrixCompute();
  48090. },
  48091. enumerable: true,
  48092. configurable: true
  48093. });
  48094. Object.defineProperty(PointLight.prototype, "direction", {
  48095. /**
  48096. * Gets the direction if it has been set.
  48097. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48098. */
  48099. get: function () {
  48100. return this._direction;
  48101. },
  48102. /**
  48103. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48104. */
  48105. set: function (value) {
  48106. var previousNeedCube = this.needCube();
  48107. this._direction = value;
  48108. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48109. this._shadowGenerator.recreateShadowMap();
  48110. }
  48111. },
  48112. enumerable: true,
  48113. configurable: true
  48114. });
  48115. /**
  48116. * Returns the string "PointLight"
  48117. * @returns the class name
  48118. */
  48119. PointLight.prototype.getClassName = function () {
  48120. return "PointLight";
  48121. };
  48122. /**
  48123. * Returns the integer 0.
  48124. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48125. */
  48126. PointLight.prototype.getTypeID = function () {
  48127. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48128. };
  48129. /**
  48130. * Specifies wether or not the shadowmap should be a cube texture.
  48131. * @returns true if the shadowmap needs to be a cube texture.
  48132. */
  48133. PointLight.prototype.needCube = function () {
  48134. return !this.direction;
  48135. };
  48136. /**
  48137. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48138. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48139. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48140. */
  48141. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48142. if (this.direction) {
  48143. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48144. }
  48145. else {
  48146. switch (faceIndex) {
  48147. case 0:
  48148. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48149. case 1:
  48150. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48151. case 2:
  48152. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48153. case 3:
  48154. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48155. case 4:
  48156. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48157. case 5:
  48158. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48159. }
  48160. }
  48161. return BABYLON.Vector3.Zero();
  48162. };
  48163. /**
  48164. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48165. * - fov = PI / 2
  48166. * - aspect ratio : 1.0
  48167. * - z-near and far equal to the active camera minZ and maxZ.
  48168. * Returns the PointLight.
  48169. */
  48170. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48171. var activeCamera = this.getScene().activeCamera;
  48172. if (!activeCamera) {
  48173. return;
  48174. }
  48175. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48176. };
  48177. PointLight.prototype._buildUniformLayout = function () {
  48178. this._uniformBuffer.addUniform("vLightData", 4);
  48179. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48180. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48181. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48182. this._uniformBuffer.addUniform("depthValues", 2);
  48183. this._uniformBuffer.create();
  48184. };
  48185. /**
  48186. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48187. * @param effect The effect to update
  48188. * @param lightIndex The index of the light in the effect to update
  48189. * @returns The point light
  48190. */
  48191. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48192. if (this.computeTransformedInformation()) {
  48193. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48194. return this;
  48195. }
  48196. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48197. return this;
  48198. };
  48199. /**
  48200. * Prepares the list of defines specific to the light type.
  48201. * @param defines the list of defines
  48202. * @param lightIndex defines the index of the light for the effect
  48203. */
  48204. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48205. defines["POINTLIGHT" + lightIndex] = true;
  48206. };
  48207. __decorate([
  48208. BABYLON.serialize()
  48209. ], PointLight.prototype, "shadowAngle", null);
  48210. return PointLight;
  48211. }(BABYLON.ShadowLight));
  48212. BABYLON.PointLight = PointLight;
  48213. })(BABYLON || (BABYLON = {}));
  48214. //# sourceMappingURL=babylon.pointLight.js.map
  48215. var BABYLON;
  48216. (function (BABYLON) {
  48217. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48218. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48219. });
  48220. /**
  48221. * A directional light is defined by a direction (what a surprise!).
  48222. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48223. * 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.
  48224. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48225. */
  48226. var DirectionalLight = /** @class */ (function (_super) {
  48227. __extends(DirectionalLight, _super);
  48228. /**
  48229. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48230. * The directional light is emitted from everywhere in the given direction.
  48231. * It can cast shawdows.
  48232. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48233. * @param name The friendly name of the light
  48234. * @param direction The direction of the light
  48235. * @param scene The scene the light belongs to
  48236. */
  48237. function DirectionalLight(name, direction, scene) {
  48238. var _this = _super.call(this, name, scene) || this;
  48239. _this._shadowFrustumSize = 0;
  48240. _this._shadowOrthoScale = 0.1;
  48241. /**
  48242. * Automatically compute the projection matrix to best fit (including all the casters)
  48243. * on each frame.
  48244. */
  48245. _this.autoUpdateExtends = true;
  48246. // Cache
  48247. _this._orthoLeft = Number.MAX_VALUE;
  48248. _this._orthoRight = Number.MIN_VALUE;
  48249. _this._orthoTop = Number.MIN_VALUE;
  48250. _this._orthoBottom = Number.MAX_VALUE;
  48251. _this.position = direction.scale(-1.0);
  48252. _this.direction = direction;
  48253. return _this;
  48254. }
  48255. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48256. /**
  48257. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48258. */
  48259. get: function () {
  48260. return this._shadowFrustumSize;
  48261. },
  48262. /**
  48263. * Specifies a fix frustum size for the shadow generation.
  48264. */
  48265. set: function (value) {
  48266. this._shadowFrustumSize = value;
  48267. this.forceProjectionMatrixCompute();
  48268. },
  48269. enumerable: true,
  48270. configurable: true
  48271. });
  48272. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48273. /**
  48274. * Gets the shadow projection scale against the optimal computed one.
  48275. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48276. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48277. */
  48278. get: function () {
  48279. return this._shadowOrthoScale;
  48280. },
  48281. /**
  48282. * Sets the shadow projection scale against the optimal computed one.
  48283. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48284. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48285. */
  48286. set: function (value) {
  48287. this._shadowOrthoScale = value;
  48288. this.forceProjectionMatrixCompute();
  48289. },
  48290. enumerable: true,
  48291. configurable: true
  48292. });
  48293. /**
  48294. * Returns the string "DirectionalLight".
  48295. * @return The class name
  48296. */
  48297. DirectionalLight.prototype.getClassName = function () {
  48298. return "DirectionalLight";
  48299. };
  48300. /**
  48301. * Returns the integer 1.
  48302. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48303. */
  48304. DirectionalLight.prototype.getTypeID = function () {
  48305. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48306. };
  48307. /**
  48308. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48309. * Returns the DirectionalLight Shadow projection matrix.
  48310. */
  48311. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48312. if (this.shadowFrustumSize > 0) {
  48313. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48314. }
  48315. else {
  48316. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48317. }
  48318. };
  48319. /**
  48320. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48321. * Returns the DirectionalLight Shadow projection matrix.
  48322. */
  48323. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48324. var activeCamera = this.getScene().activeCamera;
  48325. if (!activeCamera) {
  48326. return;
  48327. }
  48328. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48329. };
  48330. /**
  48331. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48332. * Returns the DirectionalLight Shadow projection matrix.
  48333. */
  48334. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48335. var activeCamera = this.getScene().activeCamera;
  48336. if (!activeCamera) {
  48337. return;
  48338. }
  48339. // Check extends
  48340. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48341. var tempVector3 = BABYLON.Vector3.Zero();
  48342. this._orthoLeft = Number.MAX_VALUE;
  48343. this._orthoRight = Number.MIN_VALUE;
  48344. this._orthoTop = Number.MIN_VALUE;
  48345. this._orthoBottom = Number.MAX_VALUE;
  48346. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48347. var mesh = renderList[meshIndex];
  48348. if (!mesh) {
  48349. continue;
  48350. }
  48351. var boundingInfo = mesh.getBoundingInfo();
  48352. var boundingBox = boundingInfo.boundingBox;
  48353. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48354. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48355. if (tempVector3.x < this._orthoLeft)
  48356. this._orthoLeft = tempVector3.x;
  48357. if (tempVector3.y < this._orthoBottom)
  48358. this._orthoBottom = tempVector3.y;
  48359. if (tempVector3.x > this._orthoRight)
  48360. this._orthoRight = tempVector3.x;
  48361. if (tempVector3.y > this._orthoTop)
  48362. this._orthoTop = tempVector3.y;
  48363. }
  48364. }
  48365. }
  48366. var xOffset = this._orthoRight - this._orthoLeft;
  48367. var yOffset = this._orthoTop - this._orthoBottom;
  48368. 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);
  48369. };
  48370. DirectionalLight.prototype._buildUniformLayout = function () {
  48371. this._uniformBuffer.addUniform("vLightData", 4);
  48372. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48373. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48374. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48375. this._uniformBuffer.addUniform("depthValues", 2);
  48376. this._uniformBuffer.create();
  48377. };
  48378. /**
  48379. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48380. * @param effect The effect to update
  48381. * @param lightIndex The index of the light in the effect to update
  48382. * @returns The directional light
  48383. */
  48384. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48385. if (this.computeTransformedInformation()) {
  48386. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48387. return this;
  48388. }
  48389. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48390. return this;
  48391. };
  48392. /**
  48393. * Gets the minZ used for shadow according to both the scene and the light.
  48394. *
  48395. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48396. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48397. * @param activeCamera The camera we are returning the min for
  48398. * @returns the depth min z
  48399. */
  48400. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48401. return 1;
  48402. };
  48403. /**
  48404. * Gets the maxZ used for shadow according to both the scene and the light.
  48405. *
  48406. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48407. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48408. * @param activeCamera The camera we are returning the max for
  48409. * @returns the depth max z
  48410. */
  48411. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48412. return 1;
  48413. };
  48414. /**
  48415. * Prepares the list of defines specific to the light type.
  48416. * @param defines the list of defines
  48417. * @param lightIndex defines the index of the light for the effect
  48418. */
  48419. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48420. defines["DIRLIGHT" + lightIndex] = true;
  48421. };
  48422. __decorate([
  48423. BABYLON.serialize()
  48424. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48425. __decorate([
  48426. BABYLON.serialize()
  48427. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48428. __decorate([
  48429. BABYLON.serialize()
  48430. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48431. return DirectionalLight;
  48432. }(BABYLON.ShadowLight));
  48433. BABYLON.DirectionalLight = DirectionalLight;
  48434. })(BABYLON || (BABYLON = {}));
  48435. //# sourceMappingURL=babylon.directionalLight.js.map
  48436. var BABYLON;
  48437. (function (BABYLON) {
  48438. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48439. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48440. });
  48441. /**
  48442. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48443. * These values define a cone of light starting from the position, emitting toward the direction.
  48444. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48445. * and the exponent defines the speed of the decay of the light with distance (reach).
  48446. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48447. */
  48448. var SpotLight = /** @class */ (function (_super) {
  48449. __extends(SpotLight, _super);
  48450. /**
  48451. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48452. * It can cast shadows.
  48453. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48454. * @param name The light friendly name
  48455. * @param position The position of the spot light in the scene
  48456. * @param direction The direction of the light in the scene
  48457. * @param angle The cone angle of the light in Radians
  48458. * @param exponent The light decay speed with the distance from the emission spot
  48459. * @param scene The scene the lights belongs to
  48460. */
  48461. function SpotLight(name, position, direction, angle, exponent, scene) {
  48462. var _this = _super.call(this, name, scene) || this;
  48463. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48464. _this._projectionTextureLightNear = 1e-6;
  48465. _this._projectionTextureLightFar = 1000.0;
  48466. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48467. _this._projectionTextureViewLightDirty = true;
  48468. _this._projectionTextureProjectionLightDirty = true;
  48469. _this._projectionTextureDirty = true;
  48470. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48471. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48472. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48473. _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);
  48474. _this.position = position;
  48475. _this.direction = direction;
  48476. _this.angle = angle;
  48477. _this.exponent = exponent;
  48478. return _this;
  48479. }
  48480. Object.defineProperty(SpotLight.prototype, "angle", {
  48481. /**
  48482. * Gets the cone angle of the spot light in Radians.
  48483. */
  48484. get: function () {
  48485. return this._angle;
  48486. },
  48487. /**
  48488. * Sets the cone angle of the spot light in Radians.
  48489. */
  48490. set: function (value) {
  48491. this._angle = value;
  48492. this._projectionTextureProjectionLightDirty = true;
  48493. this.forceProjectionMatrixCompute();
  48494. },
  48495. enumerable: true,
  48496. configurable: true
  48497. });
  48498. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48499. /**
  48500. * Allows scaling the angle of the light for shadow generation only.
  48501. */
  48502. get: function () {
  48503. return this._shadowAngleScale;
  48504. },
  48505. /**
  48506. * Allows scaling the angle of the light for shadow generation only.
  48507. */
  48508. set: function (value) {
  48509. this._shadowAngleScale = value;
  48510. this.forceProjectionMatrixCompute();
  48511. },
  48512. enumerable: true,
  48513. configurable: true
  48514. });
  48515. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48516. /**
  48517. * Allows reading the projecton texture
  48518. */
  48519. get: function () {
  48520. return this._projectionTextureMatrix;
  48521. },
  48522. enumerable: true,
  48523. configurable: true
  48524. });
  48525. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48526. /**
  48527. * Gets the near clip of the Spotlight for texture projection.
  48528. */
  48529. get: function () {
  48530. return this._projectionTextureLightNear;
  48531. },
  48532. /**
  48533. * Sets the near clip of the Spotlight for texture projection.
  48534. */
  48535. set: function (value) {
  48536. this._projectionTextureLightNear = value;
  48537. this._projectionTextureProjectionLightDirty = true;
  48538. },
  48539. enumerable: true,
  48540. configurable: true
  48541. });
  48542. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48543. /**
  48544. * Gets the far clip of the Spotlight for texture projection.
  48545. */
  48546. get: function () {
  48547. return this._projectionTextureLightFar;
  48548. },
  48549. /**
  48550. * Sets the far clip of the Spotlight for texture projection.
  48551. */
  48552. set: function (value) {
  48553. this._projectionTextureLightFar = value;
  48554. this._projectionTextureProjectionLightDirty = true;
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48560. /**
  48561. * Gets the Up vector of the Spotlight for texture projection.
  48562. */
  48563. get: function () {
  48564. return this._projectionTextureUpDirection;
  48565. },
  48566. /**
  48567. * Sets the Up vector of the Spotlight for texture projection.
  48568. */
  48569. set: function (value) {
  48570. this._projectionTextureUpDirection = value;
  48571. this._projectionTextureProjectionLightDirty = true;
  48572. },
  48573. enumerable: true,
  48574. configurable: true
  48575. });
  48576. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48577. /**
  48578. * Gets the projection texture of the light.
  48579. */
  48580. get: function () {
  48581. return this._projectionTexture;
  48582. },
  48583. /**
  48584. * Sets the projection texture of the light.
  48585. */
  48586. set: function (value) {
  48587. this._projectionTexture = value;
  48588. this._projectionTextureDirty = true;
  48589. },
  48590. enumerable: true,
  48591. configurable: true
  48592. });
  48593. /**
  48594. * Returns the string "SpotLight".
  48595. * @returns the class name
  48596. */
  48597. SpotLight.prototype.getClassName = function () {
  48598. return "SpotLight";
  48599. };
  48600. /**
  48601. * Returns the integer 2.
  48602. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48603. */
  48604. SpotLight.prototype.getTypeID = function () {
  48605. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48606. };
  48607. /**
  48608. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48609. */
  48610. SpotLight.prototype._setDirection = function (value) {
  48611. _super.prototype._setDirection.call(this, value);
  48612. this._projectionTextureViewLightDirty = true;
  48613. };
  48614. /**
  48615. * Overrides the position setter to recompute the projection texture view light Matrix.
  48616. */
  48617. SpotLight.prototype._setPosition = function (value) {
  48618. _super.prototype._setPosition.call(this, value);
  48619. this._projectionTextureViewLightDirty = true;
  48620. };
  48621. /**
  48622. * 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.
  48623. * Returns the SpotLight.
  48624. */
  48625. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48626. var activeCamera = this.getScene().activeCamera;
  48627. if (!activeCamera) {
  48628. return;
  48629. }
  48630. this._shadowAngleScale = this._shadowAngleScale || 1;
  48631. var angle = this._shadowAngleScale * this._angle;
  48632. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48633. };
  48634. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48635. this._projectionTextureViewLightDirty = false;
  48636. this._projectionTextureDirty = true;
  48637. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48638. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48639. };
  48640. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48641. this._projectionTextureProjectionLightDirty = false;
  48642. this._projectionTextureDirty = true;
  48643. var light_far = this.projectionTextureLightFar;
  48644. var light_near = this.projectionTextureLightNear;
  48645. var P = light_far / (light_far - light_near);
  48646. var Q = -P * light_near;
  48647. var S = 1.0 / Math.tan(this._angle / 2.0);
  48648. var A = 1.0;
  48649. 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);
  48650. };
  48651. /**
  48652. * Main function for light texture projection matrix computing.
  48653. */
  48654. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48655. this._projectionTextureDirty = false;
  48656. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48657. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48658. };
  48659. SpotLight.prototype._buildUniformLayout = function () {
  48660. this._uniformBuffer.addUniform("vLightData", 4);
  48661. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48662. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48663. this._uniformBuffer.addUniform("vLightDirection", 3);
  48664. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48665. this._uniformBuffer.addUniform("depthValues", 2);
  48666. this._uniformBuffer.create();
  48667. };
  48668. /**
  48669. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48670. * @param effect The effect to update
  48671. * @param lightIndex The index of the light in the effect to update
  48672. * @returns The spot light
  48673. */
  48674. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48675. var normalizeDirection;
  48676. if (this.computeTransformedInformation()) {
  48677. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48678. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48679. }
  48680. else {
  48681. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48682. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48683. }
  48684. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48685. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48686. if (this._projectionTextureViewLightDirty) {
  48687. this._computeProjectionTextureViewLightMatrix();
  48688. }
  48689. if (this._projectionTextureProjectionLightDirty) {
  48690. this._computeProjectionTextureProjectionLightMatrix();
  48691. }
  48692. if (this._projectionTextureDirty) {
  48693. this._computeProjectionTextureMatrix();
  48694. }
  48695. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48696. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48697. }
  48698. return this;
  48699. };
  48700. /**
  48701. * Disposes the light and the associated resources.
  48702. */
  48703. SpotLight.prototype.dispose = function () {
  48704. _super.prototype.dispose.call(this);
  48705. if (this._projectionTexture) {
  48706. this._projectionTexture.dispose();
  48707. }
  48708. };
  48709. /**
  48710. * Prepares the list of defines specific to the light type.
  48711. * @param defines the list of defines
  48712. * @param lightIndex defines the index of the light for the effect
  48713. */
  48714. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48715. defines["SPOTLIGHT" + lightIndex] = true;
  48716. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  48717. };
  48718. __decorate([
  48719. BABYLON.serialize()
  48720. ], SpotLight.prototype, "angle", null);
  48721. __decorate([
  48722. BABYLON.serialize()
  48723. ], SpotLight.prototype, "shadowAngleScale", null);
  48724. __decorate([
  48725. BABYLON.serialize()
  48726. ], SpotLight.prototype, "exponent", void 0);
  48727. __decorate([
  48728. BABYLON.serialize()
  48729. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48730. __decorate([
  48731. BABYLON.serialize()
  48732. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48733. __decorate([
  48734. BABYLON.serialize()
  48735. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48736. __decorate([
  48737. BABYLON.serializeAsTexture("projectedLightTexture")
  48738. ], SpotLight.prototype, "_projectionTexture", void 0);
  48739. return SpotLight;
  48740. }(BABYLON.ShadowLight));
  48741. BABYLON.SpotLight = SpotLight;
  48742. })(BABYLON || (BABYLON = {}));
  48743. //# sourceMappingURL=babylon.spotLight.js.map
  48744. var BABYLON;
  48745. (function (BABYLON) {
  48746. /**
  48747. * Class used to override all child animations of a given target
  48748. */
  48749. var AnimationPropertiesOverride = /** @class */ (function () {
  48750. function AnimationPropertiesOverride() {
  48751. /**
  48752. * Gets or sets a value indicating if animation blending must be used
  48753. */
  48754. this.enableBlending = false;
  48755. /**
  48756. * Gets or sets the blending speed to use when enableBlending is true
  48757. */
  48758. this.blendingSpeed = 0.01;
  48759. /**
  48760. * Gets or sets the default loop mode to use
  48761. */
  48762. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  48763. }
  48764. return AnimationPropertiesOverride;
  48765. }());
  48766. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  48767. })(BABYLON || (BABYLON = {}));
  48768. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  48769. var BABYLON;
  48770. (function (BABYLON) {
  48771. /**
  48772. * Represents the range of an animation
  48773. */
  48774. var AnimationRange = /** @class */ (function () {
  48775. /**
  48776. * Initializes the range of an animation
  48777. * @param name The name of the animation range
  48778. * @param from The starting frame of the animation
  48779. * @param to The ending frame of the animation
  48780. */
  48781. function AnimationRange(
  48782. /**The name of the animation range**/
  48783. name,
  48784. /**The starting frame of the animation */
  48785. from,
  48786. /**The ending frame of the animation*/
  48787. to) {
  48788. this.name = name;
  48789. this.from = from;
  48790. this.to = to;
  48791. }
  48792. /**
  48793. * Makes a copy of the animation range
  48794. * @returns A copy of the animation range
  48795. */
  48796. AnimationRange.prototype.clone = function () {
  48797. return new AnimationRange(this.name, this.from, this.to);
  48798. };
  48799. return AnimationRange;
  48800. }());
  48801. BABYLON.AnimationRange = AnimationRange;
  48802. /**
  48803. * Composed of a frame, and an action function
  48804. */
  48805. var AnimationEvent = /** @class */ (function () {
  48806. /**
  48807. * Initializes the animation event
  48808. * @param frame The frame for which the event is triggered
  48809. * @param action The event to perform when triggered
  48810. * @param onlyOnce Specifies if the event should be triggered only once
  48811. */
  48812. function AnimationEvent(
  48813. /** The frame for which the event is triggered **/
  48814. frame,
  48815. /** The event to perform when triggered **/
  48816. action,
  48817. /** Specifies if the event should be triggered only once**/
  48818. onlyOnce) {
  48819. this.frame = frame;
  48820. this.action = action;
  48821. this.onlyOnce = onlyOnce;
  48822. /**
  48823. * Specifies if the animation event is done
  48824. */
  48825. this.isDone = false;
  48826. }
  48827. /** @hidden */
  48828. AnimationEvent.prototype._clone = function () {
  48829. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  48830. };
  48831. return AnimationEvent;
  48832. }());
  48833. BABYLON.AnimationEvent = AnimationEvent;
  48834. /**
  48835. * A cursor which tracks a point on a path
  48836. */
  48837. var PathCursor = /** @class */ (function () {
  48838. /**
  48839. * Initializes the path cursor
  48840. * @param path The path to track
  48841. */
  48842. function PathCursor(path) {
  48843. this.path = path;
  48844. /**
  48845. * Stores path cursor callbacks for when an onchange event is triggered
  48846. */
  48847. this._onchange = new Array();
  48848. /**
  48849. * The value of the path cursor
  48850. */
  48851. this.value = 0;
  48852. /**
  48853. * The animation array of the path cursor
  48854. */
  48855. this.animations = new Array();
  48856. }
  48857. /**
  48858. * Gets the cursor point on the path
  48859. * @returns A point on the path cursor at the cursor location
  48860. */
  48861. PathCursor.prototype.getPoint = function () {
  48862. var point = this.path.getPointAtLengthPosition(this.value);
  48863. return new BABYLON.Vector3(point.x, 0, point.y);
  48864. };
  48865. /**
  48866. * Moves the cursor ahead by the step amount
  48867. * @param step The amount to move the cursor forward
  48868. * @returns This path cursor
  48869. */
  48870. PathCursor.prototype.moveAhead = function (step) {
  48871. if (step === void 0) { step = 0.002; }
  48872. this.move(step);
  48873. return this;
  48874. };
  48875. /**
  48876. * Moves the cursor behind by the step amount
  48877. * @param step The amount to move the cursor back
  48878. * @returns This path cursor
  48879. */
  48880. PathCursor.prototype.moveBack = function (step) {
  48881. if (step === void 0) { step = 0.002; }
  48882. this.move(-step);
  48883. return this;
  48884. };
  48885. /**
  48886. * Moves the cursor by the step amount
  48887. * If the step amount is greater than one, an exception is thrown
  48888. * @param step The amount to move the cursor
  48889. * @returns This path cursor
  48890. */
  48891. PathCursor.prototype.move = function (step) {
  48892. if (Math.abs(step) > 1) {
  48893. throw "step size should be less than 1.";
  48894. }
  48895. this.value += step;
  48896. this.ensureLimits();
  48897. this.raiseOnChange();
  48898. return this;
  48899. };
  48900. /**
  48901. * Ensures that the value is limited between zero and one
  48902. * @returns This path cursor
  48903. */
  48904. PathCursor.prototype.ensureLimits = function () {
  48905. while (this.value > 1) {
  48906. this.value -= 1;
  48907. }
  48908. while (this.value < 0) {
  48909. this.value += 1;
  48910. }
  48911. return this;
  48912. };
  48913. /**
  48914. * Runs onchange callbacks on change (used by the animation engine)
  48915. * @returns This path cursor
  48916. */
  48917. PathCursor.prototype.raiseOnChange = function () {
  48918. var _this = this;
  48919. this._onchange.forEach(function (f) { return f(_this); });
  48920. return this;
  48921. };
  48922. /**
  48923. * Executes a function on change
  48924. * @param f A path cursor onchange callback
  48925. * @returns This path cursor
  48926. */
  48927. PathCursor.prototype.onchange = function (f) {
  48928. this._onchange.push(f);
  48929. return this;
  48930. };
  48931. return PathCursor;
  48932. }());
  48933. BABYLON.PathCursor = PathCursor;
  48934. /**
  48935. * Enum for the animation key frame interpolation type
  48936. */
  48937. var AnimationKeyInterpolation;
  48938. (function (AnimationKeyInterpolation) {
  48939. /**
  48940. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  48941. */
  48942. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  48943. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  48944. /**
  48945. * Class used to store any kind of animation
  48946. */
  48947. var Animation = /** @class */ (function () {
  48948. /**
  48949. * Initializes the animation
  48950. * @param name Name of the animation
  48951. * @param targetProperty Property to animate
  48952. * @param framePerSecond The frames per second of the animation
  48953. * @param dataType The data type of the animation
  48954. * @param loopMode The loop mode of the animation
  48955. * @param enableBlendings Specifies if blending should be enabled
  48956. */
  48957. function Animation(
  48958. /**Name of the animation */
  48959. name,
  48960. /**Property to animate */
  48961. targetProperty,
  48962. /**The frames per second of the animation */
  48963. framePerSecond,
  48964. /**The data type of the animation */
  48965. dataType,
  48966. /**The loop mode of the animation */
  48967. loopMode,
  48968. /**Specifies if blending should be enabled */
  48969. enableBlending) {
  48970. this.name = name;
  48971. this.targetProperty = targetProperty;
  48972. this.framePerSecond = framePerSecond;
  48973. this.dataType = dataType;
  48974. this.loopMode = loopMode;
  48975. this.enableBlending = enableBlending;
  48976. /**
  48977. * @hidden Internal use only
  48978. */
  48979. this._runtimeAnimations = new Array();
  48980. /**
  48981. * The set of event that will be linked to this animation
  48982. */
  48983. this._events = new Array();
  48984. /**
  48985. * Stores the blending speed of the animation
  48986. */
  48987. this.blendingSpeed = 0.01;
  48988. /**
  48989. * Stores the animation ranges for the animation
  48990. */
  48991. this._ranges = {};
  48992. this.targetPropertyPath = targetProperty.split(".");
  48993. this.dataType = dataType;
  48994. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  48995. }
  48996. /**
  48997. * @hidden Internal use
  48998. */
  48999. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49000. var dataType = undefined;
  49001. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49002. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49003. }
  49004. else if (from instanceof BABYLON.Quaternion) {
  49005. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49006. }
  49007. else if (from instanceof BABYLON.Vector3) {
  49008. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49009. }
  49010. else if (from instanceof BABYLON.Vector2) {
  49011. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49012. }
  49013. else if (from instanceof BABYLON.Color3) {
  49014. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49015. }
  49016. else if (from instanceof BABYLON.Size) {
  49017. dataType = Animation.ANIMATIONTYPE_SIZE;
  49018. }
  49019. if (dataType == undefined) {
  49020. return null;
  49021. }
  49022. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49023. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49024. animation.setKeys(keys);
  49025. if (easingFunction !== undefined) {
  49026. animation.setEasingFunction(easingFunction);
  49027. }
  49028. return animation;
  49029. };
  49030. /**
  49031. * Sets up an animation
  49032. * @param property The property to animate
  49033. * @param animationType The animation type to apply
  49034. * @param framePerSecond The frames per second of the animation
  49035. * @param easingFunction The easing function used in the animation
  49036. * @returns The created animation
  49037. */
  49038. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49039. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49040. animation.setEasingFunction(easingFunction);
  49041. return animation;
  49042. };
  49043. /**
  49044. * Create and start an animation on a node
  49045. * @param name defines the name of the global animation that will be run on all nodes
  49046. * @param node defines the root node where the animation will take place
  49047. * @param targetProperty defines property to animate
  49048. * @param framePerSecond defines the number of frame per second yo use
  49049. * @param totalFrame defines the number of frames in total
  49050. * @param from defines the initial value
  49051. * @param to defines the final value
  49052. * @param loopMode defines which loop mode you want to use (off by default)
  49053. * @param easingFunction defines the easing function to use (linear by default)
  49054. * @param onAnimationEnd defines the callback to call when animation end
  49055. * @returns the animatable created for this animation
  49056. */
  49057. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49058. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49059. if (!animation) {
  49060. return null;
  49061. }
  49062. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49063. };
  49064. /**
  49065. * Create and start an animation on a node and its descendants
  49066. * @param name defines the name of the global animation that will be run on all nodes
  49067. * @param node defines the root node where the animation will take place
  49068. * @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
  49069. * @param targetProperty defines property to animate
  49070. * @param framePerSecond defines the number of frame per second to use
  49071. * @param totalFrame defines the number of frames in total
  49072. * @param from defines the initial value
  49073. * @param to defines the final value
  49074. * @param loopMode defines which loop mode you want to use (off by default)
  49075. * @param easingFunction defines the easing function to use (linear by default)
  49076. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49077. * @returns the list of animatables created for all nodes
  49078. * @example https://www.babylonjs-playground.com/#MH0VLI
  49079. */
  49080. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49081. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49082. if (!animation) {
  49083. return null;
  49084. }
  49085. var scene = node.getScene();
  49086. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49087. };
  49088. /**
  49089. * Creates a new animation, merges it with the existing animations and starts it
  49090. * @param name Name of the animation
  49091. * @param node Node which contains the scene that begins the animations
  49092. * @param targetProperty Specifies which property to animate
  49093. * @param framePerSecond The frames per second of the animation
  49094. * @param totalFrame The total number of frames
  49095. * @param from The frame at the beginning of the animation
  49096. * @param to The frame at the end of the animation
  49097. * @param loopMode Specifies the loop mode of the animation
  49098. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49099. * @param onAnimationEnd Callback to run once the animation is complete
  49100. * @returns Nullable animation
  49101. */
  49102. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49103. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49104. if (!animation) {
  49105. return null;
  49106. }
  49107. node.animations.push(animation);
  49108. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49109. };
  49110. /**
  49111. * Transition property of an host to the target Value
  49112. * @param property The property to transition
  49113. * @param targetValue The target Value of the property
  49114. * @param host The object where the property to animate belongs
  49115. * @param scene Scene used to run the animation
  49116. * @param frameRate Framerate (in frame/s) to use
  49117. * @param transition The transition type we want to use
  49118. * @param duration The duration of the animation, in milliseconds
  49119. * @param onAnimationEnd Callback trigger at the end of the animation
  49120. * @returns Nullable animation
  49121. */
  49122. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49123. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49124. if (duration <= 0) {
  49125. host[property] = targetValue;
  49126. if (onAnimationEnd) {
  49127. onAnimationEnd();
  49128. }
  49129. return null;
  49130. }
  49131. var endFrame = frameRate * (duration / 1000);
  49132. transition.setKeys([{
  49133. frame: 0,
  49134. value: host[property].clone ? host[property].clone() : host[property]
  49135. },
  49136. {
  49137. frame: endFrame,
  49138. value: targetValue
  49139. }]);
  49140. if (!host.animations) {
  49141. host.animations = [];
  49142. }
  49143. host.animations.push(transition);
  49144. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49145. animation.onAnimationEnd = onAnimationEnd;
  49146. return animation;
  49147. };
  49148. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49149. /**
  49150. * Return the array of runtime animations currently using this animation
  49151. */
  49152. get: function () {
  49153. return this._runtimeAnimations;
  49154. },
  49155. enumerable: true,
  49156. configurable: true
  49157. });
  49158. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49159. /**
  49160. * Specifies if any of the runtime animations are currently running
  49161. */
  49162. get: function () {
  49163. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49164. var runtimeAnimation = _a[_i];
  49165. if (!runtimeAnimation.isStopped) {
  49166. return true;
  49167. }
  49168. }
  49169. return false;
  49170. },
  49171. enumerable: true,
  49172. configurable: true
  49173. });
  49174. // Methods
  49175. /**
  49176. * Converts the animation to a string
  49177. * @param fullDetails support for multiple levels of logging within scene loading
  49178. * @returns String form of the animation
  49179. */
  49180. Animation.prototype.toString = function (fullDetails) {
  49181. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49182. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49183. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49184. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49185. if (fullDetails) {
  49186. ret += ", Ranges: {";
  49187. var first = true;
  49188. for (var name in this._ranges) {
  49189. if (first) {
  49190. ret += ", ";
  49191. first = false;
  49192. }
  49193. ret += name;
  49194. }
  49195. ret += "}";
  49196. }
  49197. return ret;
  49198. };
  49199. /**
  49200. * Add an event to this animation
  49201. * @param event Event to add
  49202. */
  49203. Animation.prototype.addEvent = function (event) {
  49204. this._events.push(event);
  49205. };
  49206. /**
  49207. * Remove all events found at the given frame
  49208. * @param frame The frame to remove events from
  49209. */
  49210. Animation.prototype.removeEvents = function (frame) {
  49211. for (var index = 0; index < this._events.length; index++) {
  49212. if (this._events[index].frame === frame) {
  49213. this._events.splice(index, 1);
  49214. index--;
  49215. }
  49216. }
  49217. };
  49218. /**
  49219. * Retrieves all the events from the animation
  49220. * @returns Events from the animation
  49221. */
  49222. Animation.prototype.getEvents = function () {
  49223. return this._events;
  49224. };
  49225. /**
  49226. * Creates an animation range
  49227. * @param name Name of the animation range
  49228. * @param from Starting frame of the animation range
  49229. * @param to Ending frame of the animation
  49230. */
  49231. Animation.prototype.createRange = function (name, from, to) {
  49232. // check name not already in use; could happen for bones after serialized
  49233. if (!this._ranges[name]) {
  49234. this._ranges[name] = new AnimationRange(name, from, to);
  49235. }
  49236. };
  49237. /**
  49238. * Deletes an animation range by name
  49239. * @param name Name of the animation range to delete
  49240. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49241. */
  49242. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49243. if (deleteFrames === void 0) { deleteFrames = true; }
  49244. var range = this._ranges[name];
  49245. if (!range) {
  49246. return;
  49247. }
  49248. if (deleteFrames) {
  49249. var from = range.from;
  49250. var to = range.to;
  49251. // this loop MUST go high to low for multiple splices to work
  49252. for (var key = this._keys.length - 1; key >= 0; key--) {
  49253. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49254. this._keys.splice(key, 1);
  49255. }
  49256. }
  49257. }
  49258. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49259. };
  49260. /**
  49261. * Gets the animation range by name, or null if not defined
  49262. * @param name Name of the animation range
  49263. * @returns Nullable animation range
  49264. */
  49265. Animation.prototype.getRange = function (name) {
  49266. return this._ranges[name];
  49267. };
  49268. /**
  49269. * Gets the key frames from the animation
  49270. * @returns The key frames of the animation
  49271. */
  49272. Animation.prototype.getKeys = function () {
  49273. return this._keys;
  49274. };
  49275. /**
  49276. * Gets the highest frame rate of the animation
  49277. * @returns Highest frame rate of the animation
  49278. */
  49279. Animation.prototype.getHighestFrame = function () {
  49280. var ret = 0;
  49281. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49282. if (ret < this._keys[key].frame) {
  49283. ret = this._keys[key].frame;
  49284. }
  49285. }
  49286. return ret;
  49287. };
  49288. /**
  49289. * Gets the easing function of the animation
  49290. * @returns Easing function of the animation
  49291. */
  49292. Animation.prototype.getEasingFunction = function () {
  49293. return this._easingFunction;
  49294. };
  49295. /**
  49296. * Sets the easing function of the animation
  49297. * @param easingFunction A custom mathematical formula for animation
  49298. */
  49299. Animation.prototype.setEasingFunction = function (easingFunction) {
  49300. this._easingFunction = easingFunction;
  49301. };
  49302. /**
  49303. * Interpolates a scalar linearly
  49304. * @param startValue Start value of the animation curve
  49305. * @param endValue End value of the animation curve
  49306. * @param gradient Scalar amount to interpolate
  49307. * @returns Interpolated scalar value
  49308. */
  49309. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49310. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49311. };
  49312. /**
  49313. * Interpolates a scalar cubically
  49314. * @param startValue Start value of the animation curve
  49315. * @param outTangent End tangent of the animation
  49316. * @param endValue End value of the animation curve
  49317. * @param inTangent Start tangent of the animation curve
  49318. * @param gradient Scalar amount to interpolate
  49319. * @returns Interpolated scalar value
  49320. */
  49321. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49322. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49323. };
  49324. /**
  49325. * Interpolates a quaternion using a spherical linear interpolation
  49326. * @param startValue Start value of the animation curve
  49327. * @param endValue End value of the animation curve
  49328. * @param gradient Scalar amount to interpolate
  49329. * @returns Interpolated quaternion value
  49330. */
  49331. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49332. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49333. };
  49334. /**
  49335. * Interpolates a quaternion cubically
  49336. * @param startValue Start value of the animation curve
  49337. * @param outTangent End tangent of the animation curve
  49338. * @param endValue End value of the animation curve
  49339. * @param inTangent Start tangent of the animation curve
  49340. * @param gradient Scalar amount to interpolate
  49341. * @returns Interpolated quaternion value
  49342. */
  49343. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49344. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49345. };
  49346. /**
  49347. * Interpolates a Vector3 linearl
  49348. * @param startValue Start value of the animation curve
  49349. * @param endValue End value of the animation curve
  49350. * @param gradient Scalar amount to interpolate
  49351. * @returns Interpolated scalar value
  49352. */
  49353. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49354. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49355. };
  49356. /**
  49357. * Interpolates a Vector3 cubically
  49358. * @param startValue Start value of the animation curve
  49359. * @param outTangent End tangent of the animation
  49360. * @param endValue End value of the animation curve
  49361. * @param inTangent Start tangent of the animation curve
  49362. * @param gradient Scalar amount to interpolate
  49363. * @returns InterpolatedVector3 value
  49364. */
  49365. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49366. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49367. };
  49368. /**
  49369. * Interpolates a Vector2 linearly
  49370. * @param startValue Start value of the animation curve
  49371. * @param endValue End value of the animation curve
  49372. * @param gradient Scalar amount to interpolate
  49373. * @returns Interpolated Vector2 value
  49374. */
  49375. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49376. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49377. };
  49378. /**
  49379. * Interpolates a Vector2 cubically
  49380. * @param startValue Start value of the animation curve
  49381. * @param outTangent End tangent of the animation
  49382. * @param endValue End value of the animation curve
  49383. * @param inTangent Start tangent of the animation curve
  49384. * @param gradient Scalar amount to interpolate
  49385. * @returns Interpolated Vector2 value
  49386. */
  49387. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49388. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49389. };
  49390. /**
  49391. * Interpolates a size linearly
  49392. * @param startValue Start value of the animation curve
  49393. * @param endValue End value of the animation curve
  49394. * @param gradient Scalar amount to interpolate
  49395. * @returns Interpolated Size value
  49396. */
  49397. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49398. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49399. };
  49400. /**
  49401. * Interpolates a Color3 linearly
  49402. * @param startValue Start value of the animation curve
  49403. * @param endValue End value of the animation curve
  49404. * @param gradient Scalar amount to interpolate
  49405. * @returns Interpolated Color3 value
  49406. */
  49407. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49408. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49409. };
  49410. /**
  49411. * @hidden Internal use only
  49412. */
  49413. Animation.prototype._getKeyValue = function (value) {
  49414. if (typeof value === "function") {
  49415. return value();
  49416. }
  49417. return value;
  49418. };
  49419. /**
  49420. * @hidden Internal use only
  49421. */
  49422. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49423. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49424. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49425. }
  49426. var keys = this.getKeys();
  49427. // Try to get a hash to find the right key
  49428. 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));
  49429. if (keys[startKeyIndex].frame >= currentFrame) {
  49430. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49431. startKeyIndex--;
  49432. }
  49433. }
  49434. for (var key = startKeyIndex; key < keys.length; key++) {
  49435. var endKey = keys[key + 1];
  49436. if (endKey.frame >= currentFrame) {
  49437. var startKey = keys[key];
  49438. var startValue = this._getKeyValue(startKey.value);
  49439. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49440. return startValue;
  49441. }
  49442. var endValue = this._getKeyValue(endKey.value);
  49443. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49444. var frameDelta = endKey.frame - startKey.frame;
  49445. // gradient : percent of currentFrame between the frame inf and the frame sup
  49446. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49447. // check for easingFunction and correction of gradient
  49448. var easingFunction = this.getEasingFunction();
  49449. if (easingFunction != null) {
  49450. gradient = easingFunction.ease(gradient);
  49451. }
  49452. switch (this.dataType) {
  49453. // Float
  49454. case Animation.ANIMATIONTYPE_FLOAT:
  49455. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49456. switch (loopMode) {
  49457. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49458. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49459. return floatValue;
  49460. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49461. return offsetValue * repeatCount + floatValue;
  49462. }
  49463. break;
  49464. // Quaternion
  49465. case Animation.ANIMATIONTYPE_QUATERNION:
  49466. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49467. switch (loopMode) {
  49468. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49469. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49470. return quatValue;
  49471. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49472. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49473. }
  49474. return quatValue;
  49475. // Vector3
  49476. case Animation.ANIMATIONTYPE_VECTOR3:
  49477. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49478. switch (loopMode) {
  49479. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49480. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49481. return vec3Value;
  49482. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49483. return vec3Value.add(offsetValue.scale(repeatCount));
  49484. }
  49485. // Vector2
  49486. case Animation.ANIMATIONTYPE_VECTOR2:
  49487. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49488. switch (loopMode) {
  49489. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49490. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49491. return vec2Value;
  49492. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49493. return vec2Value.add(offsetValue.scale(repeatCount));
  49494. }
  49495. // Size
  49496. case Animation.ANIMATIONTYPE_SIZE:
  49497. switch (loopMode) {
  49498. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49499. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49500. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49501. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49502. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49503. }
  49504. // Color3
  49505. case Animation.ANIMATIONTYPE_COLOR3:
  49506. switch (loopMode) {
  49507. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49508. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49509. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49510. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49511. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49512. }
  49513. // Matrix
  49514. case Animation.ANIMATIONTYPE_MATRIX:
  49515. switch (loopMode) {
  49516. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49517. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49518. if (Animation.AllowMatricesInterpolation) {
  49519. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49520. }
  49521. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49522. return startValue;
  49523. }
  49524. default:
  49525. break;
  49526. }
  49527. break;
  49528. }
  49529. }
  49530. return this._getKeyValue(keys[keys.length - 1].value);
  49531. };
  49532. /**
  49533. * Defines the function to use to interpolate matrices
  49534. * @param startValue defines the start matrix
  49535. * @param endValue defines the end matrix
  49536. * @param gradient defines the gradient between both matrices
  49537. * @param result defines an optional target matrix where to store the interpolation
  49538. * @returns the interpolated matrix
  49539. */
  49540. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49541. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49542. if (result) {
  49543. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49544. return result;
  49545. }
  49546. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49547. }
  49548. if (result) {
  49549. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49550. return result;
  49551. }
  49552. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49553. };
  49554. /**
  49555. * Makes a copy of the animation
  49556. * @returns Cloned animation
  49557. */
  49558. Animation.prototype.clone = function () {
  49559. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49560. clone.enableBlending = this.enableBlending;
  49561. clone.blendingSpeed = this.blendingSpeed;
  49562. if (this._keys) {
  49563. clone.setKeys(this._keys);
  49564. }
  49565. if (this._ranges) {
  49566. clone._ranges = {};
  49567. for (var name in this._ranges) {
  49568. var range = this._ranges[name];
  49569. if (!range) {
  49570. continue;
  49571. }
  49572. clone._ranges[name] = range.clone();
  49573. }
  49574. }
  49575. return clone;
  49576. };
  49577. /**
  49578. * Sets the key frames of the animation
  49579. * @param values The animation key frames to set
  49580. */
  49581. Animation.prototype.setKeys = function (values) {
  49582. this._keys = values.slice(0);
  49583. };
  49584. /**
  49585. * Serializes the animation to an object
  49586. * @returns Serialized object
  49587. */
  49588. Animation.prototype.serialize = function () {
  49589. var serializationObject = {};
  49590. serializationObject.name = this.name;
  49591. serializationObject.property = this.targetProperty;
  49592. serializationObject.framePerSecond = this.framePerSecond;
  49593. serializationObject.dataType = this.dataType;
  49594. serializationObject.loopBehavior = this.loopMode;
  49595. serializationObject.enableBlending = this.enableBlending;
  49596. serializationObject.blendingSpeed = this.blendingSpeed;
  49597. var dataType = this.dataType;
  49598. serializationObject.keys = [];
  49599. var keys = this.getKeys();
  49600. for (var index = 0; index < keys.length; index++) {
  49601. var animationKey = keys[index];
  49602. var key = {};
  49603. key.frame = animationKey.frame;
  49604. switch (dataType) {
  49605. case Animation.ANIMATIONTYPE_FLOAT:
  49606. key.values = [animationKey.value];
  49607. break;
  49608. case Animation.ANIMATIONTYPE_QUATERNION:
  49609. case Animation.ANIMATIONTYPE_MATRIX:
  49610. case Animation.ANIMATIONTYPE_VECTOR3:
  49611. case Animation.ANIMATIONTYPE_COLOR3:
  49612. key.values = animationKey.value.asArray();
  49613. break;
  49614. }
  49615. serializationObject.keys.push(key);
  49616. }
  49617. serializationObject.ranges = [];
  49618. for (var name in this._ranges) {
  49619. var source = this._ranges[name];
  49620. if (!source) {
  49621. continue;
  49622. }
  49623. var range = {};
  49624. range.name = name;
  49625. range.from = source.from;
  49626. range.to = source.to;
  49627. serializationObject.ranges.push(range);
  49628. }
  49629. return serializationObject;
  49630. };
  49631. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49632. /**
  49633. * Get the float animation type
  49634. */
  49635. get: function () {
  49636. return Animation._ANIMATIONTYPE_FLOAT;
  49637. },
  49638. enumerable: true,
  49639. configurable: true
  49640. });
  49641. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49642. /**
  49643. * Get the Vector3 animation type
  49644. */
  49645. get: function () {
  49646. return Animation._ANIMATIONTYPE_VECTOR3;
  49647. },
  49648. enumerable: true,
  49649. configurable: true
  49650. });
  49651. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49652. /**
  49653. * Get the Vectpr2 animation type
  49654. */
  49655. get: function () {
  49656. return Animation._ANIMATIONTYPE_VECTOR2;
  49657. },
  49658. enumerable: true,
  49659. configurable: true
  49660. });
  49661. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49662. /**
  49663. * Get the Size animation type
  49664. */
  49665. get: function () {
  49666. return Animation._ANIMATIONTYPE_SIZE;
  49667. },
  49668. enumerable: true,
  49669. configurable: true
  49670. });
  49671. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49672. /**
  49673. * Get the Quaternion animation type
  49674. */
  49675. get: function () {
  49676. return Animation._ANIMATIONTYPE_QUATERNION;
  49677. },
  49678. enumerable: true,
  49679. configurable: true
  49680. });
  49681. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49682. /**
  49683. * Get the Matrix animation type
  49684. */
  49685. get: function () {
  49686. return Animation._ANIMATIONTYPE_MATRIX;
  49687. },
  49688. enumerable: true,
  49689. configurable: true
  49690. });
  49691. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49692. /**
  49693. * Get the Color3 animation type
  49694. */
  49695. get: function () {
  49696. return Animation._ANIMATIONTYPE_COLOR3;
  49697. },
  49698. enumerable: true,
  49699. configurable: true
  49700. });
  49701. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49702. /**
  49703. * Get the Relative Loop Mode
  49704. */
  49705. get: function () {
  49706. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49707. },
  49708. enumerable: true,
  49709. configurable: true
  49710. });
  49711. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49712. /**
  49713. * Get the Cycle Loop Mode
  49714. */
  49715. get: function () {
  49716. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49717. },
  49718. enumerable: true,
  49719. configurable: true
  49720. });
  49721. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49722. /**
  49723. * Get the Constant Loop Mode
  49724. */
  49725. get: function () {
  49726. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49727. },
  49728. enumerable: true,
  49729. configurable: true
  49730. });
  49731. /** @hidden */
  49732. Animation._UniversalLerp = function (left, right, amount) {
  49733. var constructor = left.constructor;
  49734. if (constructor.Lerp) { // Lerp supported
  49735. return constructor.Lerp(left, right, amount);
  49736. }
  49737. else if (constructor.Slerp) { // Slerp supported
  49738. return constructor.Slerp(left, right, amount);
  49739. }
  49740. else if (left.toFixed) { // Number
  49741. return left * (1.0 - amount) + amount * right;
  49742. }
  49743. else { // Blending not supported
  49744. return right;
  49745. }
  49746. };
  49747. /**
  49748. * Parses an animation object and creates an animation
  49749. * @param parsedAnimation Parsed animation object
  49750. * @returns Animation object
  49751. */
  49752. Animation.Parse = function (parsedAnimation) {
  49753. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49754. var dataType = parsedAnimation.dataType;
  49755. var keys = [];
  49756. var data;
  49757. var index;
  49758. if (parsedAnimation.enableBlending) {
  49759. animation.enableBlending = parsedAnimation.enableBlending;
  49760. }
  49761. if (parsedAnimation.blendingSpeed) {
  49762. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49763. }
  49764. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49765. var key = parsedAnimation.keys[index];
  49766. var inTangent;
  49767. var outTangent;
  49768. switch (dataType) {
  49769. case Animation.ANIMATIONTYPE_FLOAT:
  49770. data = key.values[0];
  49771. if (key.values.length >= 1) {
  49772. inTangent = key.values[1];
  49773. }
  49774. if (key.values.length >= 2) {
  49775. outTangent = key.values[2];
  49776. }
  49777. break;
  49778. case Animation.ANIMATIONTYPE_QUATERNION:
  49779. data = BABYLON.Quaternion.FromArray(key.values);
  49780. if (key.values.length >= 8) {
  49781. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49782. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49783. inTangent = _inTangent;
  49784. }
  49785. }
  49786. if (key.values.length >= 12) {
  49787. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49788. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49789. outTangent = _outTangent;
  49790. }
  49791. }
  49792. break;
  49793. case Animation.ANIMATIONTYPE_MATRIX:
  49794. data = BABYLON.Matrix.FromArray(key.values);
  49795. break;
  49796. case Animation.ANIMATIONTYPE_COLOR3:
  49797. data = BABYLON.Color3.FromArray(key.values);
  49798. break;
  49799. case Animation.ANIMATIONTYPE_VECTOR3:
  49800. default:
  49801. data = BABYLON.Vector3.FromArray(key.values);
  49802. break;
  49803. }
  49804. var keyData = {};
  49805. keyData.frame = key.frame;
  49806. keyData.value = data;
  49807. if (inTangent != undefined) {
  49808. keyData.inTangent = inTangent;
  49809. }
  49810. if (outTangent != undefined) {
  49811. keyData.outTangent = outTangent;
  49812. }
  49813. keys.push(keyData);
  49814. }
  49815. animation.setKeys(keys);
  49816. if (parsedAnimation.ranges) {
  49817. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49818. data = parsedAnimation.ranges[index];
  49819. animation.createRange(data.name, data.from, data.to);
  49820. }
  49821. }
  49822. return animation;
  49823. };
  49824. /**
  49825. * Appends the serialized animations from the source animations
  49826. * @param source Source containing the animations
  49827. * @param destination Target to store the animations
  49828. */
  49829. Animation.AppendSerializedAnimations = function (source, destination) {
  49830. if (source.animations) {
  49831. destination.animations = [];
  49832. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49833. var animation = source.animations[animationIndex];
  49834. destination.animations.push(animation.serialize());
  49835. }
  49836. }
  49837. };
  49838. /**
  49839. * Use matrix interpolation instead of using direct key value when animating matrices
  49840. */
  49841. Animation.AllowMatricesInterpolation = false;
  49842. /**
  49843. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  49844. */
  49845. Animation.AllowMatrixDecomposeForInterpolation = true;
  49846. // Statics
  49847. /**
  49848. * Float animation type
  49849. */
  49850. Animation._ANIMATIONTYPE_FLOAT = 0;
  49851. /**
  49852. * Vector3 animation type
  49853. */
  49854. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49855. /**
  49856. * Quaternion animation type
  49857. */
  49858. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49859. /**
  49860. * Matrix animation type
  49861. */
  49862. Animation._ANIMATIONTYPE_MATRIX = 3;
  49863. /**
  49864. * Color3 animation type
  49865. */
  49866. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49867. /**
  49868. * Vector2 animation type
  49869. */
  49870. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49871. /**
  49872. * Size animation type
  49873. */
  49874. Animation._ANIMATIONTYPE_SIZE = 6;
  49875. /**
  49876. * Relative Loop Mode
  49877. */
  49878. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49879. /**
  49880. * Cycle Loop Mode
  49881. */
  49882. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49883. /**
  49884. * Constant Loop Mode
  49885. */
  49886. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49887. return Animation;
  49888. }());
  49889. BABYLON.Animation = Animation;
  49890. })(BABYLON || (BABYLON = {}));
  49891. //# sourceMappingURL=babylon.animation.js.map
  49892. var BABYLON;
  49893. (function (BABYLON) {
  49894. /**
  49895. * This class defines the direct association between an animation and a target
  49896. */
  49897. var TargetedAnimation = /** @class */ (function () {
  49898. function TargetedAnimation() {
  49899. }
  49900. return TargetedAnimation;
  49901. }());
  49902. BABYLON.TargetedAnimation = TargetedAnimation;
  49903. /**
  49904. * Use this class to create coordinated animations on multiple targets
  49905. */
  49906. var AnimationGroup = /** @class */ (function () {
  49907. function AnimationGroup(name, scene) {
  49908. if (scene === void 0) { scene = null; }
  49909. this.name = name;
  49910. this._targetedAnimations = new Array();
  49911. this._animatables = new Array();
  49912. this._from = Number.MAX_VALUE;
  49913. this._to = -Number.MAX_VALUE;
  49914. this._speedRatio = 1;
  49915. this.onAnimationEndObservable = new BABYLON.Observable();
  49916. /**
  49917. * This observable will notify when all animations have ended.
  49918. */
  49919. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  49920. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49921. this._scene.animationGroups.push(this);
  49922. }
  49923. Object.defineProperty(AnimationGroup.prototype, "from", {
  49924. /**
  49925. * Gets the first frame
  49926. */
  49927. get: function () {
  49928. return this._from;
  49929. },
  49930. enumerable: true,
  49931. configurable: true
  49932. });
  49933. Object.defineProperty(AnimationGroup.prototype, "to", {
  49934. /**
  49935. * Gets the last frame
  49936. */
  49937. get: function () {
  49938. return this._to;
  49939. },
  49940. enumerable: true,
  49941. configurable: true
  49942. });
  49943. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49944. /**
  49945. * Define if the animations are started
  49946. */
  49947. get: function () {
  49948. return this._isStarted;
  49949. },
  49950. enumerable: true,
  49951. configurable: true
  49952. });
  49953. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  49954. /**
  49955. * Gets or sets the speed ratio to use for all animations
  49956. */
  49957. get: function () {
  49958. return this._speedRatio;
  49959. },
  49960. /**
  49961. * Gets or sets the speed ratio to use for all animations
  49962. */
  49963. set: function (value) {
  49964. if (this._speedRatio === value) {
  49965. return;
  49966. }
  49967. this._speedRatio = value;
  49968. for (var index = 0; index < this._animatables.length; index++) {
  49969. var animatable = this._animatables[index];
  49970. animatable.speedRatio = this._speedRatio;
  49971. }
  49972. },
  49973. enumerable: true,
  49974. configurable: true
  49975. });
  49976. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  49977. /**
  49978. * Gets the targeted animations for this animation group
  49979. */
  49980. get: function () {
  49981. return this._targetedAnimations;
  49982. },
  49983. enumerable: true,
  49984. configurable: true
  49985. });
  49986. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  49987. /**
  49988. * returning the list of animatables controlled by this animation group.
  49989. */
  49990. get: function () {
  49991. return this._animatables;
  49992. },
  49993. enumerable: true,
  49994. configurable: true
  49995. });
  49996. /**
  49997. * Add an animation (with its target) in the group
  49998. * @param animation defines the animation we want to add
  49999. * @param target defines the target of the animation
  50000. * @returns the {BABYLON.TargetedAnimation} object
  50001. */
  50002. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50003. var targetedAnimation = {
  50004. animation: animation,
  50005. target: target
  50006. };
  50007. var keys = animation.getKeys();
  50008. if (this._from > keys[0].frame) {
  50009. this._from = keys[0].frame;
  50010. }
  50011. if (this._to < keys[keys.length - 1].frame) {
  50012. this._to = keys[keys.length - 1].frame;
  50013. }
  50014. this._targetedAnimations.push(targetedAnimation);
  50015. return targetedAnimation;
  50016. };
  50017. /**
  50018. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50019. * It can add constant keys at begin or end
  50020. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50021. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50022. */
  50023. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50024. if (beginFrame === void 0) { beginFrame = null; }
  50025. if (endFrame === void 0) { endFrame = null; }
  50026. if (beginFrame == null)
  50027. beginFrame = this._from;
  50028. if (endFrame == null)
  50029. endFrame = this._to;
  50030. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50031. var targetedAnimation = this._targetedAnimations[index];
  50032. var keys = targetedAnimation.animation.getKeys();
  50033. var startKey = keys[0];
  50034. var endKey = keys[keys.length - 1];
  50035. if (startKey.frame > beginFrame) {
  50036. var newKey = {
  50037. frame: beginFrame,
  50038. value: startKey.value,
  50039. inTangent: startKey.inTangent,
  50040. outTangent: startKey.outTangent,
  50041. interpolation: startKey.interpolation
  50042. };
  50043. keys.splice(0, 0, newKey);
  50044. }
  50045. if (endKey.frame < endFrame) {
  50046. var newKey = {
  50047. frame: endFrame,
  50048. value: endKey.value,
  50049. inTangent: endKey.outTangent,
  50050. outTangent: endKey.outTangent,
  50051. interpolation: endKey.interpolation
  50052. };
  50053. keys.push(newKey);
  50054. }
  50055. }
  50056. this._from = beginFrame;
  50057. this._to = endFrame;
  50058. return this;
  50059. };
  50060. /**
  50061. * Start all animations on given targets
  50062. * @param loop defines if animations must loop
  50063. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50064. * @param from defines the from key (optional)
  50065. * @param to defines the to key (optional)
  50066. * @returns the current animation group
  50067. */
  50068. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50069. var _this = this;
  50070. if (loop === void 0) { loop = false; }
  50071. if (speedRatio === void 0) { speedRatio = 1; }
  50072. if (this._isStarted || this._targetedAnimations.length === 0) {
  50073. return this;
  50074. }
  50075. var _loop_1 = function (targetedAnimation) {
  50076. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50077. animatable.onAnimationEnd = function () {
  50078. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50079. _this._checkAnimationGroupEnded(animatable);
  50080. };
  50081. this_1._animatables.push(animatable);
  50082. };
  50083. var this_1 = this;
  50084. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50085. var targetedAnimation = _a[_i];
  50086. _loop_1(targetedAnimation);
  50087. }
  50088. this._speedRatio = speedRatio;
  50089. this._isStarted = true;
  50090. return this;
  50091. };
  50092. /**
  50093. * Pause all animations
  50094. */
  50095. AnimationGroup.prototype.pause = function () {
  50096. if (!this._isStarted) {
  50097. return this;
  50098. }
  50099. for (var index = 0; index < this._animatables.length; index++) {
  50100. var animatable = this._animatables[index];
  50101. animatable.pause();
  50102. }
  50103. return this;
  50104. };
  50105. /**
  50106. * Play all animations to initial state
  50107. * This function will start() the animations if they were not started or will restart() them if they were paused
  50108. * @param loop defines if animations must loop
  50109. */
  50110. AnimationGroup.prototype.play = function (loop) {
  50111. // only if all animatables are ready and exist
  50112. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50113. if (loop !== undefined) {
  50114. for (var index = 0; index < this._animatables.length; index++) {
  50115. var animatable = this._animatables[index];
  50116. animatable.loopAnimation = loop;
  50117. }
  50118. }
  50119. this.restart();
  50120. }
  50121. else {
  50122. this.stop();
  50123. this.start(loop, this._speedRatio);
  50124. }
  50125. return this;
  50126. };
  50127. /**
  50128. * Reset all animations to initial state
  50129. */
  50130. AnimationGroup.prototype.reset = function () {
  50131. if (!this._isStarted) {
  50132. return this;
  50133. }
  50134. for (var index = 0; index < this._animatables.length; index++) {
  50135. var animatable = this._animatables[index];
  50136. animatable.reset();
  50137. }
  50138. return this;
  50139. };
  50140. /**
  50141. * Restart animations from key 0
  50142. */
  50143. AnimationGroup.prototype.restart = function () {
  50144. if (!this._isStarted) {
  50145. return this;
  50146. }
  50147. for (var index = 0; index < this._animatables.length; index++) {
  50148. var animatable = this._animatables[index];
  50149. animatable.restart();
  50150. }
  50151. return this;
  50152. };
  50153. /**
  50154. * Stop all animations
  50155. */
  50156. AnimationGroup.prototype.stop = function () {
  50157. if (!this._isStarted) {
  50158. return this;
  50159. }
  50160. var list = this._animatables.slice();
  50161. for (var index = 0; index < list.length; index++) {
  50162. list[index].stop();
  50163. }
  50164. this._isStarted = false;
  50165. return this;
  50166. };
  50167. /**
  50168. * Set animation weight for all animatables
  50169. * @param weight defines the weight to use
  50170. * @return the animationGroup
  50171. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50172. */
  50173. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50174. for (var index = 0; index < this._animatables.length; index++) {
  50175. var animatable = this._animatables[index];
  50176. animatable.weight = weight;
  50177. }
  50178. return this;
  50179. };
  50180. /**
  50181. * Synchronize and normalize all animatables with a source animatable
  50182. * @param root defines the root animatable to synchronize with
  50183. * @return the animationGroup
  50184. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50185. */
  50186. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50187. for (var index = 0; index < this._animatables.length; index++) {
  50188. var animatable = this._animatables[index];
  50189. animatable.syncWith(root);
  50190. }
  50191. return this;
  50192. };
  50193. /**
  50194. * Goes to a specific frame in this animation group
  50195. * @param frame the frame number to go to
  50196. * @return the animationGroup
  50197. */
  50198. AnimationGroup.prototype.goToFrame = function (frame) {
  50199. if (!this._isStarted) {
  50200. return this;
  50201. }
  50202. for (var index = 0; index < this._animatables.length; index++) {
  50203. var animatable = this._animatables[index];
  50204. animatable.goToFrame(frame);
  50205. }
  50206. return this;
  50207. };
  50208. /**
  50209. * Dispose all associated resources
  50210. */
  50211. AnimationGroup.prototype.dispose = function () {
  50212. this._targetedAnimations = [];
  50213. this._animatables = [];
  50214. var index = this._scene.animationGroups.indexOf(this);
  50215. if (index > -1) {
  50216. this._scene.animationGroups.splice(index, 1);
  50217. }
  50218. };
  50219. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50220. // animatable should be taken out of the array
  50221. var idx = this._animatables.indexOf(animatable);
  50222. if (idx > -1) {
  50223. this._animatables.splice(idx, 1);
  50224. }
  50225. // all animatables were removed? animation group ended!
  50226. if (this._animatables.length === 0) {
  50227. this._isStarted = false;
  50228. this.onAnimationGroupEndObservable.notifyObservers(this);
  50229. }
  50230. };
  50231. return AnimationGroup;
  50232. }());
  50233. BABYLON.AnimationGroup = AnimationGroup;
  50234. })(BABYLON || (BABYLON = {}));
  50235. //# sourceMappingURL=babylon.animationGroup.js.map
  50236. var BABYLON;
  50237. (function (BABYLON) {
  50238. /**
  50239. * Defines a runtime animation
  50240. */
  50241. var RuntimeAnimation = /** @class */ (function () {
  50242. /**
  50243. * Create a new RuntimeAnimation object
  50244. * @param target defines the target of the animation
  50245. * @param animation defines the source animation object
  50246. * @param scene defines the hosting scene
  50247. * @param host defines the initiating Animatable
  50248. */
  50249. function RuntimeAnimation(target, animation, scene, host) {
  50250. var _this = this;
  50251. this._events = new Array();
  50252. /**
  50253. * The current frame of the runtime animation
  50254. */
  50255. this._currentFrame = 0;
  50256. /**
  50257. * The original value of the runtime animation
  50258. */
  50259. this._originalValue = new Array();
  50260. /**
  50261. * The offsets cache of the runtime animation
  50262. */
  50263. this._offsetsCache = {};
  50264. /**
  50265. * The high limits cache of the runtime animation
  50266. */
  50267. this._highLimitsCache = {};
  50268. /**
  50269. * Specifies if the runtime animation has been stopped
  50270. */
  50271. this._stopped = false;
  50272. /**
  50273. * The blending factor of the runtime animation
  50274. */
  50275. this._blendingFactor = 0;
  50276. /**
  50277. * The target path of the runtime animation
  50278. */
  50279. this._targetPath = "";
  50280. /**
  50281. * The weight of the runtime animation
  50282. */
  50283. this._weight = 1.0;
  50284. /**
  50285. * The ratio offset of the runtime animation
  50286. */
  50287. this._ratioOffset = 0;
  50288. /**
  50289. * The previous delay of the runtime animation
  50290. */
  50291. this._previousDelay = 0;
  50292. /**
  50293. * The previous ratio of the runtime animation
  50294. */
  50295. this._previousRatio = 0;
  50296. this._animation = animation;
  50297. this._target = target;
  50298. this._scene = scene;
  50299. this._host = host;
  50300. animation._runtimeAnimations.push(this);
  50301. // Cloning events locally
  50302. var events = animation.getEvents();
  50303. if (events && events.length > 0) {
  50304. events.forEach(function (e) {
  50305. _this._events.push(e._clone());
  50306. });
  50307. }
  50308. }
  50309. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50310. /**
  50311. * Gets the current frame of the runtime animation
  50312. */
  50313. get: function () {
  50314. return this._currentFrame;
  50315. },
  50316. enumerable: true,
  50317. configurable: true
  50318. });
  50319. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50320. /**
  50321. * Gets the weight of the runtime animation
  50322. */
  50323. get: function () {
  50324. return this._weight;
  50325. },
  50326. enumerable: true,
  50327. configurable: true
  50328. });
  50329. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50330. /**
  50331. * Gets the current value of the runtime animation
  50332. */
  50333. get: function () {
  50334. return this._currentValue;
  50335. },
  50336. enumerable: true,
  50337. configurable: true
  50338. });
  50339. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50340. /**
  50341. * Gets the target path of the runtime animation
  50342. */
  50343. get: function () {
  50344. return this._targetPath;
  50345. },
  50346. enumerable: true,
  50347. configurable: true
  50348. });
  50349. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50350. /**
  50351. * Gets the actual target of the runtime animation
  50352. */
  50353. get: function () {
  50354. return this._activeTarget;
  50355. },
  50356. enumerable: true,
  50357. configurable: true
  50358. });
  50359. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50360. /**
  50361. * Gets the animation from the runtime animation
  50362. */
  50363. get: function () {
  50364. return this._animation;
  50365. },
  50366. enumerable: true,
  50367. configurable: true
  50368. });
  50369. /**
  50370. * Resets the runtime animation to the beginning
  50371. * @param restoreOriginal defines whether to restore the target property to the original value
  50372. */
  50373. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50374. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50375. if (restoreOriginal) {
  50376. if (this._target instanceof Array) {
  50377. var index = 0;
  50378. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50379. var target = _a[_i];
  50380. if (this._originalValue[index] !== undefined) {
  50381. this._setValue(target, this._originalValue[index], -1);
  50382. }
  50383. index++;
  50384. }
  50385. }
  50386. else {
  50387. if (this._originalValue[0] !== undefined) {
  50388. this._setValue(this._target, this._originalValue[0], -1);
  50389. }
  50390. }
  50391. }
  50392. this._offsetsCache = {};
  50393. this._highLimitsCache = {};
  50394. this._currentFrame = 0;
  50395. this._blendingFactor = 0;
  50396. this._originalValue = new Array();
  50397. // Events
  50398. for (var index = 0; index < this._events.length; index++) {
  50399. this._events[index].isDone = false;
  50400. }
  50401. };
  50402. /**
  50403. * Specifies if the runtime animation is stopped
  50404. * @returns Boolean specifying if the runtime animation is stopped
  50405. */
  50406. RuntimeAnimation.prototype.isStopped = function () {
  50407. return this._stopped;
  50408. };
  50409. /**
  50410. * Disposes of the runtime animation
  50411. */
  50412. RuntimeAnimation.prototype.dispose = function () {
  50413. var index = this._animation.runtimeAnimations.indexOf(this);
  50414. if (index > -1) {
  50415. this._animation.runtimeAnimations.splice(index, 1);
  50416. }
  50417. };
  50418. /**
  50419. * Interpolates the animation from the current frame
  50420. * @param currentFrame The frame to interpolate the animation to
  50421. * @param repeatCount The number of times that the animation should loop
  50422. * @param loopMode The type of looping mode to use
  50423. * @param offsetValue Animation offset value
  50424. * @param highLimitValue The high limit value
  50425. * @returns The interpolated value
  50426. */
  50427. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50428. this._currentFrame = currentFrame;
  50429. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50430. this._workValue = BABYLON.Matrix.Zero();
  50431. }
  50432. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50433. };
  50434. /**
  50435. * Apply the interpolated value to the target
  50436. * @param currentValue defines the value computed by the animation
  50437. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50438. */
  50439. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50440. if (weight === void 0) { weight = 1.0; }
  50441. if (this._target instanceof Array) {
  50442. var index = 0;
  50443. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50444. var target = _a[_i];
  50445. this._setValue(target, currentValue, weight, index);
  50446. index++;
  50447. }
  50448. }
  50449. else {
  50450. this._setValue(this._target, currentValue, weight);
  50451. }
  50452. };
  50453. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50454. if (targetIndex === void 0) { targetIndex = 0; }
  50455. // Set value
  50456. var path;
  50457. var destination;
  50458. var targetPropertyPath = this._animation.targetPropertyPath;
  50459. if (targetPropertyPath.length > 1) {
  50460. var property = target[targetPropertyPath[0]];
  50461. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50462. property = property[targetPropertyPath[index]];
  50463. }
  50464. path = targetPropertyPath[targetPropertyPath.length - 1];
  50465. destination = property;
  50466. }
  50467. else {
  50468. path = targetPropertyPath[0];
  50469. destination = target;
  50470. }
  50471. this._targetPath = path;
  50472. this._activeTarget = destination;
  50473. this._weight = weight;
  50474. if (this._originalValue[targetIndex] === undefined) {
  50475. var originalValue = void 0;
  50476. if (destination.getRestPose && path === "_matrix") { // For bones
  50477. originalValue = destination.getRestPose();
  50478. }
  50479. else {
  50480. originalValue = destination[path];
  50481. }
  50482. if (originalValue && originalValue.clone) {
  50483. this._originalValue[targetIndex] = originalValue.clone();
  50484. }
  50485. else {
  50486. this._originalValue[targetIndex] = originalValue;
  50487. }
  50488. }
  50489. // Blending
  50490. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50491. if (enableBlending && this._blendingFactor <= 1.0) {
  50492. if (!this._originalBlendValue) {
  50493. var originalValue = destination[path];
  50494. if (originalValue.clone) {
  50495. this._originalBlendValue = originalValue.clone();
  50496. }
  50497. else {
  50498. this._originalBlendValue = originalValue;
  50499. }
  50500. }
  50501. if (this._originalBlendValue.m) { // Matrix
  50502. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50503. if (this._currentValue) {
  50504. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50505. }
  50506. else {
  50507. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50508. }
  50509. }
  50510. else {
  50511. if (this._currentValue) {
  50512. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50513. }
  50514. else {
  50515. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50516. }
  50517. }
  50518. }
  50519. else {
  50520. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50521. }
  50522. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50523. this._blendingFactor += blendingSpeed;
  50524. }
  50525. else {
  50526. this._currentValue = currentValue;
  50527. }
  50528. if (weight !== -1.0) {
  50529. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50530. }
  50531. else {
  50532. destination[path] = this._currentValue;
  50533. }
  50534. if (target.markAsDirty) {
  50535. target.markAsDirty(this._animation.targetProperty);
  50536. }
  50537. };
  50538. /**
  50539. * Gets the loop pmode of the runtime animation
  50540. * @returns Loop Mode
  50541. */
  50542. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50543. if (this._target && this._target.animationPropertiesOverride) {
  50544. return this._target.animationPropertiesOverride.loopMode;
  50545. }
  50546. return this._animation.loopMode;
  50547. };
  50548. /**
  50549. * Move the current animation to a given frame
  50550. * @param frame defines the frame to move to
  50551. */
  50552. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50553. var keys = this._animation.getKeys();
  50554. if (frame < keys[0].frame) {
  50555. frame = keys[0].frame;
  50556. }
  50557. else if (frame > keys[keys.length - 1].frame) {
  50558. frame = keys[keys.length - 1].frame;
  50559. }
  50560. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50561. this.setValue(currentValue, -1);
  50562. };
  50563. /**
  50564. * @hidden Internal use only
  50565. */
  50566. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50567. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50568. this._ratioOffset = this._previousRatio - newRatio;
  50569. };
  50570. /**
  50571. * Execute the current animation
  50572. * @param delay defines the delay to add to the current frame
  50573. * @param from defines the lower bound of the animation range
  50574. * @param to defines the upper bound of the animation range
  50575. * @param loop defines if the current animation must loop
  50576. * @param speedRatio defines the current speed ratio
  50577. * @param weight defines the weight of the animation (default is -1 so no weight)
  50578. * @returns a boolean indicating if the animation is running
  50579. */
  50580. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50581. if (weight === void 0) { weight = -1.0; }
  50582. var targetPropertyPath = this._animation.targetPropertyPath;
  50583. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50584. this._stopped = true;
  50585. return false;
  50586. }
  50587. var returnValue = true;
  50588. var keys = this._animation.getKeys();
  50589. // Adding a start key at frame 0 if missing
  50590. if (keys[0].frame !== 0) {
  50591. var newKey = { frame: 0, value: keys[0].value };
  50592. keys.splice(0, 0, newKey);
  50593. }
  50594. // Adding a duplicate key when there is only one key at frame zero
  50595. else if (keys.length === 1) {
  50596. var newKey = { frame: 0.001, value: keys[0].value };
  50597. keys.push(newKey);
  50598. }
  50599. // Check limits
  50600. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50601. from = keys[0].frame;
  50602. }
  50603. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50604. to = keys[keys.length - 1].frame;
  50605. }
  50606. //to and from cannot be the same key
  50607. if (from === to) {
  50608. if (from > keys[0].frame) {
  50609. from--;
  50610. }
  50611. else if (to < keys[keys.length - 1].frame) {
  50612. to++;
  50613. }
  50614. }
  50615. // Compute ratio
  50616. var range = to - from;
  50617. var offsetValue;
  50618. // ratio represents the frame delta between from and to
  50619. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50620. var highLimitValue = 0;
  50621. this._previousDelay = delay;
  50622. this._previousRatio = ratio;
  50623. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50624. returnValue = false;
  50625. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50626. }
  50627. else {
  50628. // Get max value if required
  50629. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50630. var keyOffset = to.toString() + from.toString();
  50631. if (!this._offsetsCache[keyOffset]) {
  50632. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50633. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50634. switch (this._animation.dataType) {
  50635. // Float
  50636. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50637. this._offsetsCache[keyOffset] = toValue - fromValue;
  50638. break;
  50639. // Quaternion
  50640. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50641. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50642. break;
  50643. // Vector3
  50644. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50645. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50646. // Vector2
  50647. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50648. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50649. // Size
  50650. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50651. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50652. // Color3
  50653. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50654. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50655. default:
  50656. break;
  50657. }
  50658. this._highLimitsCache[keyOffset] = toValue;
  50659. }
  50660. highLimitValue = this._highLimitsCache[keyOffset];
  50661. offsetValue = this._offsetsCache[keyOffset];
  50662. }
  50663. }
  50664. if (offsetValue === undefined) {
  50665. switch (this._animation.dataType) {
  50666. // Float
  50667. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50668. offsetValue = 0;
  50669. break;
  50670. // Quaternion
  50671. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50672. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50673. break;
  50674. // Vector3
  50675. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50676. offsetValue = BABYLON.Vector3.Zero();
  50677. break;
  50678. // Vector2
  50679. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50680. offsetValue = BABYLON.Vector2.Zero();
  50681. break;
  50682. // Size
  50683. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50684. offsetValue = BABYLON.Size.Zero();
  50685. break;
  50686. // Color3
  50687. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50688. offsetValue = BABYLON.Color3.Black();
  50689. }
  50690. }
  50691. // Compute value
  50692. var repeatCount = (ratio / range) >> 0;
  50693. var currentFrame = returnValue ? from + ratio % range : to;
  50694. // Need to normalize?
  50695. if (this._host && this._host.syncRoot) {
  50696. var syncRoot = this._host.syncRoot;
  50697. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50698. currentFrame = from + (to - from) * hostNormalizedFrame;
  50699. }
  50700. // Reset events if looping
  50701. var events = this._events;
  50702. if (range > 0 && this.currentFrame > currentFrame ||
  50703. range < 0 && this.currentFrame < currentFrame) {
  50704. // Need to reset animation events
  50705. for (var index = 0; index < events.length; index++) {
  50706. if (!events[index].onlyOnce) {
  50707. // reset event, the animation is looping
  50708. events[index].isDone = false;
  50709. }
  50710. }
  50711. }
  50712. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50713. // Set value
  50714. this.setValue(currentValue, weight);
  50715. // Check events
  50716. for (var index = 0; index < events.length; index++) {
  50717. // Make sure current frame has passed event frame and that event frame is within the current range
  50718. // Also, handle both forward and reverse animations
  50719. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50720. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50721. var event = events[index];
  50722. if (!event.isDone) {
  50723. // If event should be done only once, remove it.
  50724. if (event.onlyOnce) {
  50725. events.splice(index, 1);
  50726. index--;
  50727. }
  50728. event.isDone = true;
  50729. event.action();
  50730. } // Don't do anything if the event has already be done.
  50731. }
  50732. }
  50733. if (!returnValue) {
  50734. this._stopped = true;
  50735. }
  50736. return returnValue;
  50737. };
  50738. return RuntimeAnimation;
  50739. }());
  50740. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50741. })(BABYLON || (BABYLON = {}));
  50742. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50743. var BABYLON;
  50744. (function (BABYLON) {
  50745. /**
  50746. * Class used to store an actual running animation
  50747. */
  50748. var Animatable = /** @class */ (function () {
  50749. /**
  50750. * Creates a new Animatable
  50751. * @param scene defines the hosting scene
  50752. * @param target defines the target object
  50753. * @param fromFrame defines the starting frame number (default is 0)
  50754. * @param toFrame defines the ending frame number (default is 100)
  50755. * @param loopAnimation defines if the animation must loop (default is false)
  50756. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  50757. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  50758. * @param animations defines a group of animation to add to the new Animatable
  50759. */
  50760. function Animatable(scene,
  50761. /** defines the target object */
  50762. target,
  50763. /** defines the starting frame number (default is 0) */
  50764. fromFrame,
  50765. /** defines the ending frame number (default is 100) */
  50766. toFrame,
  50767. /** defines if the animation must loop (default is false) */
  50768. loopAnimation, speedRatio,
  50769. /** defines a callback to call when animation ends if it is not looping */
  50770. onAnimationEnd, animations) {
  50771. if (fromFrame === void 0) { fromFrame = 0; }
  50772. if (toFrame === void 0) { toFrame = 100; }
  50773. if (loopAnimation === void 0) { loopAnimation = false; }
  50774. if (speedRatio === void 0) { speedRatio = 1.0; }
  50775. this.target = target;
  50776. this.fromFrame = fromFrame;
  50777. this.toFrame = toFrame;
  50778. this.loopAnimation = loopAnimation;
  50779. this.onAnimationEnd = onAnimationEnd;
  50780. this._localDelayOffset = null;
  50781. this._pausedDelay = null;
  50782. this._runtimeAnimations = new Array();
  50783. this._paused = false;
  50784. this._speedRatio = 1;
  50785. this._weight = -1.0;
  50786. /**
  50787. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  50788. * This will only apply for non looping animation (default is true)
  50789. */
  50790. this.disposeOnEnd = true;
  50791. /**
  50792. * Gets a boolean indicating if the animation has started
  50793. */
  50794. this.animationStarted = false;
  50795. /**
  50796. * Observer raised when the animation ends
  50797. */
  50798. this.onAnimationEndObservable = new BABYLON.Observable();
  50799. this._scene = scene;
  50800. if (animations) {
  50801. this.appendAnimations(target, animations);
  50802. }
  50803. this._speedRatio = speedRatio;
  50804. scene._activeAnimatables.push(this);
  50805. }
  50806. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50807. /**
  50808. * Gets the root Animatable used to synchronize and normalize animations
  50809. */
  50810. get: function () {
  50811. return this._syncRoot;
  50812. },
  50813. enumerable: true,
  50814. configurable: true
  50815. });
  50816. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50817. /**
  50818. * Gets the current frame of the first RuntimeAnimation
  50819. * Used to synchronize Animatables
  50820. */
  50821. get: function () {
  50822. if (this._runtimeAnimations.length === 0) {
  50823. return 0;
  50824. }
  50825. return this._runtimeAnimations[0].currentFrame;
  50826. },
  50827. enumerable: true,
  50828. configurable: true
  50829. });
  50830. Object.defineProperty(Animatable.prototype, "weight", {
  50831. /**
  50832. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50833. */
  50834. get: function () {
  50835. return this._weight;
  50836. },
  50837. set: function (value) {
  50838. if (value === -1) { // -1 is ok and means no weight
  50839. this._weight = -1;
  50840. return;
  50841. }
  50842. // Else weight must be in [0, 1] range
  50843. this._weight = Math.min(Math.max(value, 0), 1.0);
  50844. },
  50845. enumerable: true,
  50846. configurable: true
  50847. });
  50848. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50849. /**
  50850. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50851. */
  50852. get: function () {
  50853. return this._speedRatio;
  50854. },
  50855. set: function (value) {
  50856. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50857. var animation = this._runtimeAnimations[index];
  50858. animation._prepareForSpeedRatioChange(value);
  50859. }
  50860. this._speedRatio = value;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. // Methods
  50866. /**
  50867. * Synchronize and normalize current Animatable with a source Animatable
  50868. * This is useful when using animation weights and when animations are not of the same length
  50869. * @param root defines the root Animatable to synchronize with
  50870. * @returns the current Animatable
  50871. */
  50872. Animatable.prototype.syncWith = function (root) {
  50873. this._syncRoot = root;
  50874. if (root) {
  50875. // Make sure this animatable will animate after the root
  50876. var index = this._scene._activeAnimatables.indexOf(this);
  50877. if (index > -1) {
  50878. this._scene._activeAnimatables.splice(index, 1);
  50879. this._scene._activeAnimatables.push(this);
  50880. }
  50881. }
  50882. return this;
  50883. };
  50884. /**
  50885. * Gets the list of runtime animations
  50886. * @returns an array of RuntimeAnimation
  50887. */
  50888. Animatable.prototype.getAnimations = function () {
  50889. return this._runtimeAnimations;
  50890. };
  50891. /**
  50892. * Adds more animations to the current animatable
  50893. * @param target defines the target of the animations
  50894. * @param animations defines the new animations to add
  50895. */
  50896. Animatable.prototype.appendAnimations = function (target, animations) {
  50897. for (var index = 0; index < animations.length; index++) {
  50898. var animation = animations[index];
  50899. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50900. }
  50901. };
  50902. /**
  50903. * Gets the source animation for a specific property
  50904. * @param property defines the propertyu to look for
  50905. * @returns null or the source animation for the given property
  50906. */
  50907. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50908. var runtimeAnimations = this._runtimeAnimations;
  50909. for (var index = 0; index < runtimeAnimations.length; index++) {
  50910. if (runtimeAnimations[index].animation.targetProperty === property) {
  50911. return runtimeAnimations[index].animation;
  50912. }
  50913. }
  50914. return null;
  50915. };
  50916. /**
  50917. * Gets the runtime animation for a specific property
  50918. * @param property defines the propertyu to look for
  50919. * @returns null or the runtime animation for the given property
  50920. */
  50921. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50922. var runtimeAnimations = this._runtimeAnimations;
  50923. for (var index = 0; index < runtimeAnimations.length; index++) {
  50924. if (runtimeAnimations[index].animation.targetProperty === property) {
  50925. return runtimeAnimations[index];
  50926. }
  50927. }
  50928. return null;
  50929. };
  50930. /**
  50931. * Resets the animatable to its original state
  50932. */
  50933. Animatable.prototype.reset = function () {
  50934. var runtimeAnimations = this._runtimeAnimations;
  50935. for (var index = 0; index < runtimeAnimations.length; index++) {
  50936. runtimeAnimations[index].reset(true);
  50937. }
  50938. this._localDelayOffset = null;
  50939. this._pausedDelay = null;
  50940. };
  50941. /**
  50942. * Allows the animatable to blend with current running animations
  50943. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  50944. * @param blendingSpeed defines the blending speed to use
  50945. */
  50946. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50947. var runtimeAnimations = this._runtimeAnimations;
  50948. for (var index = 0; index < runtimeAnimations.length; index++) {
  50949. runtimeAnimations[index].animation.enableBlending = true;
  50950. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  50951. }
  50952. };
  50953. /**
  50954. * Disable animation blending
  50955. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  50956. */
  50957. Animatable.prototype.disableBlending = function () {
  50958. var runtimeAnimations = this._runtimeAnimations;
  50959. for (var index = 0; index < runtimeAnimations.length; index++) {
  50960. runtimeAnimations[index].animation.enableBlending = false;
  50961. }
  50962. };
  50963. /**
  50964. * Jump directly to a given frame
  50965. * @param frame defines the frame to jump to
  50966. */
  50967. Animatable.prototype.goToFrame = function (frame) {
  50968. var runtimeAnimations = this._runtimeAnimations;
  50969. if (runtimeAnimations[0]) {
  50970. var fps = runtimeAnimations[0].animation.framePerSecond;
  50971. var currentFrame = runtimeAnimations[0].currentFrame;
  50972. var adjustTime = frame - currentFrame;
  50973. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  50974. if (this._localDelayOffset === null) {
  50975. this._localDelayOffset = 0;
  50976. }
  50977. this._localDelayOffset -= delay;
  50978. }
  50979. for (var index = 0; index < runtimeAnimations.length; index++) {
  50980. runtimeAnimations[index].goToFrame(frame);
  50981. }
  50982. };
  50983. /**
  50984. * Pause the animation
  50985. */
  50986. Animatable.prototype.pause = function () {
  50987. if (this._paused) {
  50988. return;
  50989. }
  50990. this._paused = true;
  50991. };
  50992. /**
  50993. * Restart the animation
  50994. */
  50995. Animatable.prototype.restart = function () {
  50996. this._paused = false;
  50997. };
  50998. Animatable.prototype._raiseOnAnimationEnd = function () {
  50999. if (this.onAnimationEnd) {
  51000. this.onAnimationEnd();
  51001. }
  51002. this.onAnimationEndObservable.notifyObservers(this);
  51003. };
  51004. /**
  51005. * Stop and delete the current animation
  51006. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51007. * @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)
  51008. */
  51009. Animatable.prototype.stop = function (animationName, targetMask) {
  51010. if (animationName || targetMask) {
  51011. var idx = this._scene._activeAnimatables.indexOf(this);
  51012. if (idx > -1) {
  51013. var runtimeAnimations = this._runtimeAnimations;
  51014. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51015. var runtimeAnimation = runtimeAnimations[index];
  51016. if (animationName && runtimeAnimation.animation.name != animationName) {
  51017. continue;
  51018. }
  51019. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51020. continue;
  51021. }
  51022. runtimeAnimation.dispose();
  51023. runtimeAnimations.splice(index, 1);
  51024. }
  51025. if (runtimeAnimations.length == 0) {
  51026. this._scene._activeAnimatables.splice(idx, 1);
  51027. this._raiseOnAnimationEnd();
  51028. }
  51029. }
  51030. }
  51031. else {
  51032. var index = this._scene._activeAnimatables.indexOf(this);
  51033. if (index > -1) {
  51034. this._scene._activeAnimatables.splice(index, 1);
  51035. var runtimeAnimations = this._runtimeAnimations;
  51036. for (var index = 0; index < runtimeAnimations.length; index++) {
  51037. runtimeAnimations[index].dispose();
  51038. }
  51039. this._raiseOnAnimationEnd();
  51040. }
  51041. }
  51042. };
  51043. /**
  51044. * Wait asynchronously for the animation to end
  51045. * @returns a promise which will be fullfilled when the animation ends
  51046. */
  51047. Animatable.prototype.waitAsync = function () {
  51048. var _this = this;
  51049. return new Promise(function (resolve, reject) {
  51050. _this.onAnimationEndObservable.add(function () {
  51051. resolve(_this);
  51052. }, undefined, undefined, _this, true);
  51053. });
  51054. };
  51055. /** @hidden */
  51056. Animatable.prototype._animate = function (delay) {
  51057. if (this._paused) {
  51058. this.animationStarted = false;
  51059. if (this._pausedDelay === null) {
  51060. this._pausedDelay = delay;
  51061. }
  51062. return true;
  51063. }
  51064. if (this._localDelayOffset === null) {
  51065. this._localDelayOffset = delay;
  51066. this._pausedDelay = null;
  51067. }
  51068. else if (this._pausedDelay !== null) {
  51069. this._localDelayOffset += delay - this._pausedDelay;
  51070. this._pausedDelay = null;
  51071. }
  51072. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51073. return true;
  51074. }
  51075. // Animating
  51076. var running = false;
  51077. var runtimeAnimations = this._runtimeAnimations;
  51078. var index;
  51079. for (index = 0; index < runtimeAnimations.length; index++) {
  51080. var animation = runtimeAnimations[index];
  51081. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51082. running = running || isRunning;
  51083. }
  51084. this.animationStarted = running;
  51085. if (!running) {
  51086. if (this.disposeOnEnd) {
  51087. // Remove from active animatables
  51088. index = this._scene._activeAnimatables.indexOf(this);
  51089. this._scene._activeAnimatables.splice(index, 1);
  51090. // Dispose all runtime animations
  51091. for (index = 0; index < runtimeAnimations.length; index++) {
  51092. runtimeAnimations[index].dispose();
  51093. }
  51094. }
  51095. this._raiseOnAnimationEnd();
  51096. if (this.disposeOnEnd) {
  51097. this.onAnimationEnd = null;
  51098. this.onAnimationEndObservable.clear();
  51099. }
  51100. }
  51101. return running;
  51102. };
  51103. return Animatable;
  51104. }());
  51105. BABYLON.Animatable = Animatable;
  51106. })(BABYLON || (BABYLON = {}));
  51107. //# sourceMappingURL=babylon.animatable.js.map
  51108. var BABYLON;
  51109. (function (BABYLON) {
  51110. var EasingFunction = /** @class */ (function () {
  51111. function EasingFunction() {
  51112. // Properties
  51113. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51114. }
  51115. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51116. get: function () {
  51117. return EasingFunction._EASINGMODE_EASEIN;
  51118. },
  51119. enumerable: true,
  51120. configurable: true
  51121. });
  51122. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51123. get: function () {
  51124. return EasingFunction._EASINGMODE_EASEOUT;
  51125. },
  51126. enumerable: true,
  51127. configurable: true
  51128. });
  51129. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51130. get: function () {
  51131. return EasingFunction._EASINGMODE_EASEINOUT;
  51132. },
  51133. enumerable: true,
  51134. configurable: true
  51135. });
  51136. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51137. var n = Math.min(Math.max(easingMode, 0), 2);
  51138. this._easingMode = n;
  51139. };
  51140. EasingFunction.prototype.getEasingMode = function () {
  51141. return this._easingMode;
  51142. };
  51143. EasingFunction.prototype.easeInCore = function (gradient) {
  51144. throw new Error('You must implement this method');
  51145. };
  51146. EasingFunction.prototype.ease = function (gradient) {
  51147. switch (this._easingMode) {
  51148. case EasingFunction.EASINGMODE_EASEIN:
  51149. return this.easeInCore(gradient);
  51150. case EasingFunction.EASINGMODE_EASEOUT:
  51151. return (1 - this.easeInCore(1 - gradient));
  51152. }
  51153. if (gradient >= 0.5) {
  51154. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51155. }
  51156. return (this.easeInCore(gradient * 2) * 0.5);
  51157. };
  51158. //Statics
  51159. EasingFunction._EASINGMODE_EASEIN = 0;
  51160. EasingFunction._EASINGMODE_EASEOUT = 1;
  51161. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51162. return EasingFunction;
  51163. }());
  51164. BABYLON.EasingFunction = EasingFunction;
  51165. var CircleEase = /** @class */ (function (_super) {
  51166. __extends(CircleEase, _super);
  51167. function CircleEase() {
  51168. return _super !== null && _super.apply(this, arguments) || this;
  51169. }
  51170. CircleEase.prototype.easeInCore = function (gradient) {
  51171. gradient = Math.max(0, Math.min(1, gradient));
  51172. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51173. };
  51174. return CircleEase;
  51175. }(EasingFunction));
  51176. BABYLON.CircleEase = CircleEase;
  51177. var BackEase = /** @class */ (function (_super) {
  51178. __extends(BackEase, _super);
  51179. function BackEase(amplitude) {
  51180. if (amplitude === void 0) { amplitude = 1; }
  51181. var _this = _super.call(this) || this;
  51182. _this.amplitude = amplitude;
  51183. return _this;
  51184. }
  51185. BackEase.prototype.easeInCore = function (gradient) {
  51186. var num = Math.max(0, this.amplitude);
  51187. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51188. };
  51189. return BackEase;
  51190. }(EasingFunction));
  51191. BABYLON.BackEase = BackEase;
  51192. var BounceEase = /** @class */ (function (_super) {
  51193. __extends(BounceEase, _super);
  51194. function BounceEase(bounces, bounciness) {
  51195. if (bounces === void 0) { bounces = 3; }
  51196. if (bounciness === void 0) { bounciness = 2; }
  51197. var _this = _super.call(this) || this;
  51198. _this.bounces = bounces;
  51199. _this.bounciness = bounciness;
  51200. return _this;
  51201. }
  51202. BounceEase.prototype.easeInCore = function (gradient) {
  51203. var y = Math.max(0.0, this.bounces);
  51204. var bounciness = this.bounciness;
  51205. if (bounciness <= 1.0) {
  51206. bounciness = 1.001;
  51207. }
  51208. var num9 = Math.pow(bounciness, y);
  51209. var num5 = 1.0 - bounciness;
  51210. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51211. var num15 = gradient * num4;
  51212. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51213. var num3 = Math.floor(num65);
  51214. var num13 = num3 + 1.0;
  51215. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51216. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51217. var num7 = (num8 + num12) * 0.5;
  51218. var num6 = gradient - num7;
  51219. var num2 = num7 - num8;
  51220. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51221. };
  51222. return BounceEase;
  51223. }(EasingFunction));
  51224. BABYLON.BounceEase = BounceEase;
  51225. var CubicEase = /** @class */ (function (_super) {
  51226. __extends(CubicEase, _super);
  51227. function CubicEase() {
  51228. return _super !== null && _super.apply(this, arguments) || this;
  51229. }
  51230. CubicEase.prototype.easeInCore = function (gradient) {
  51231. return (gradient * gradient * gradient);
  51232. };
  51233. return CubicEase;
  51234. }(EasingFunction));
  51235. BABYLON.CubicEase = CubicEase;
  51236. var ElasticEase = /** @class */ (function (_super) {
  51237. __extends(ElasticEase, _super);
  51238. function ElasticEase(oscillations, springiness) {
  51239. if (oscillations === void 0) { oscillations = 3; }
  51240. if (springiness === void 0) { springiness = 3; }
  51241. var _this = _super.call(this) || this;
  51242. _this.oscillations = oscillations;
  51243. _this.springiness = springiness;
  51244. return _this;
  51245. }
  51246. ElasticEase.prototype.easeInCore = function (gradient) {
  51247. var num2;
  51248. var num3 = Math.max(0.0, this.oscillations);
  51249. var num = Math.max(0.0, this.springiness);
  51250. if (num == 0) {
  51251. num2 = gradient;
  51252. }
  51253. else {
  51254. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51255. }
  51256. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51257. };
  51258. return ElasticEase;
  51259. }(EasingFunction));
  51260. BABYLON.ElasticEase = ElasticEase;
  51261. var ExponentialEase = /** @class */ (function (_super) {
  51262. __extends(ExponentialEase, _super);
  51263. function ExponentialEase(exponent) {
  51264. if (exponent === void 0) { exponent = 2; }
  51265. var _this = _super.call(this) || this;
  51266. _this.exponent = exponent;
  51267. return _this;
  51268. }
  51269. ExponentialEase.prototype.easeInCore = function (gradient) {
  51270. if (this.exponent <= 0) {
  51271. return gradient;
  51272. }
  51273. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51274. };
  51275. return ExponentialEase;
  51276. }(EasingFunction));
  51277. BABYLON.ExponentialEase = ExponentialEase;
  51278. var PowerEase = /** @class */ (function (_super) {
  51279. __extends(PowerEase, _super);
  51280. function PowerEase(power) {
  51281. if (power === void 0) { power = 2; }
  51282. var _this = _super.call(this) || this;
  51283. _this.power = power;
  51284. return _this;
  51285. }
  51286. PowerEase.prototype.easeInCore = function (gradient) {
  51287. var y = Math.max(0.0, this.power);
  51288. return Math.pow(gradient, y);
  51289. };
  51290. return PowerEase;
  51291. }(EasingFunction));
  51292. BABYLON.PowerEase = PowerEase;
  51293. var QuadraticEase = /** @class */ (function (_super) {
  51294. __extends(QuadraticEase, _super);
  51295. function QuadraticEase() {
  51296. return _super !== null && _super.apply(this, arguments) || this;
  51297. }
  51298. QuadraticEase.prototype.easeInCore = function (gradient) {
  51299. return (gradient * gradient);
  51300. };
  51301. return QuadraticEase;
  51302. }(EasingFunction));
  51303. BABYLON.QuadraticEase = QuadraticEase;
  51304. var QuarticEase = /** @class */ (function (_super) {
  51305. __extends(QuarticEase, _super);
  51306. function QuarticEase() {
  51307. return _super !== null && _super.apply(this, arguments) || this;
  51308. }
  51309. QuarticEase.prototype.easeInCore = function (gradient) {
  51310. return (gradient * gradient * gradient * gradient);
  51311. };
  51312. return QuarticEase;
  51313. }(EasingFunction));
  51314. BABYLON.QuarticEase = QuarticEase;
  51315. var QuinticEase = /** @class */ (function (_super) {
  51316. __extends(QuinticEase, _super);
  51317. function QuinticEase() {
  51318. return _super !== null && _super.apply(this, arguments) || this;
  51319. }
  51320. QuinticEase.prototype.easeInCore = function (gradient) {
  51321. return (gradient * gradient * gradient * gradient * gradient);
  51322. };
  51323. return QuinticEase;
  51324. }(EasingFunction));
  51325. BABYLON.QuinticEase = QuinticEase;
  51326. var SineEase = /** @class */ (function (_super) {
  51327. __extends(SineEase, _super);
  51328. function SineEase() {
  51329. return _super !== null && _super.apply(this, arguments) || this;
  51330. }
  51331. SineEase.prototype.easeInCore = function (gradient) {
  51332. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51333. };
  51334. return SineEase;
  51335. }(EasingFunction));
  51336. BABYLON.SineEase = SineEase;
  51337. var BezierCurveEase = /** @class */ (function (_super) {
  51338. __extends(BezierCurveEase, _super);
  51339. function BezierCurveEase(x1, y1, x2, y2) {
  51340. if (x1 === void 0) { x1 = 0; }
  51341. if (y1 === void 0) { y1 = 0; }
  51342. if (x2 === void 0) { x2 = 1; }
  51343. if (y2 === void 0) { y2 = 1; }
  51344. var _this = _super.call(this) || this;
  51345. _this.x1 = x1;
  51346. _this.y1 = y1;
  51347. _this.x2 = x2;
  51348. _this.y2 = y2;
  51349. return _this;
  51350. }
  51351. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51352. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51353. };
  51354. return BezierCurveEase;
  51355. }(EasingFunction));
  51356. BABYLON.BezierCurveEase = BezierCurveEase;
  51357. })(BABYLON || (BABYLON = {}));
  51358. //# sourceMappingURL=babylon.easing.js.map
  51359. var BABYLON;
  51360. (function (BABYLON) {
  51361. /**
  51362. * A Condition applied to an Action
  51363. */
  51364. var Condition = /** @class */ (function () {
  51365. /**
  51366. * Creates a new Condition
  51367. * @param actionManager the manager of the action the condition is applied to
  51368. */
  51369. function Condition(actionManager) {
  51370. this._actionManager = actionManager;
  51371. }
  51372. /**
  51373. * Check if the current condition is valid
  51374. * @returns a boolean
  51375. */
  51376. Condition.prototype.isValid = function () {
  51377. return true;
  51378. };
  51379. /**
  51380. * Internal only
  51381. * @hidden
  51382. */
  51383. Condition.prototype._getProperty = function (propertyPath) {
  51384. return this._actionManager._getProperty(propertyPath);
  51385. };
  51386. /**
  51387. * Internal only
  51388. * @hidden
  51389. */
  51390. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51391. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51392. };
  51393. /**
  51394. * Serialize placeholder for child classes
  51395. * @returns the serialized object
  51396. */
  51397. Condition.prototype.serialize = function () {
  51398. };
  51399. /**
  51400. * Internal only
  51401. * @hidden
  51402. */
  51403. Condition.prototype._serialize = function (serializedCondition) {
  51404. return {
  51405. type: 2,
  51406. children: [],
  51407. name: serializedCondition.name,
  51408. properties: serializedCondition.properties
  51409. };
  51410. };
  51411. return Condition;
  51412. }());
  51413. BABYLON.Condition = Condition;
  51414. /**
  51415. * Defines specific conditional operators as extensions of Condition
  51416. */
  51417. var ValueCondition = /** @class */ (function (_super) {
  51418. __extends(ValueCondition, _super);
  51419. /**
  51420. * Creates a new ValueCondition
  51421. * @param actionManager manager for the action the condition applies to
  51422. * @param target for the action
  51423. * @param propertyPath path to specify the property of the target the conditional operator uses
  51424. * @param value the value compared by the conditional operator against the current value of the property
  51425. * @param operator the conditional operator, default ValueCondition.IsEqual
  51426. */
  51427. function ValueCondition(actionManager, target,
  51428. /** path to specify the property of the target the conditional operator uses */
  51429. propertyPath,
  51430. /** the value compared by the conditional operator against the current value of the property */
  51431. value,
  51432. /** the conditional operator, default ValueCondition.IsEqual */
  51433. operator) {
  51434. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51435. var _this = _super.call(this, actionManager) || this;
  51436. _this.propertyPath = propertyPath;
  51437. _this.value = value;
  51438. _this.operator = operator;
  51439. _this._target = target;
  51440. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51441. _this._property = _this._getProperty(_this.propertyPath);
  51442. return _this;
  51443. }
  51444. Object.defineProperty(ValueCondition, "IsEqual", {
  51445. /**
  51446. * returns the number for IsEqual
  51447. */
  51448. get: function () {
  51449. return ValueCondition._IsEqual;
  51450. },
  51451. enumerable: true,
  51452. configurable: true
  51453. });
  51454. Object.defineProperty(ValueCondition, "IsDifferent", {
  51455. /**
  51456. * Returns the number for IsDifferent
  51457. */
  51458. get: function () {
  51459. return ValueCondition._IsDifferent;
  51460. },
  51461. enumerable: true,
  51462. configurable: true
  51463. });
  51464. Object.defineProperty(ValueCondition, "IsGreater", {
  51465. /**
  51466. * Returns the number for IsGreater
  51467. */
  51468. get: function () {
  51469. return ValueCondition._IsGreater;
  51470. },
  51471. enumerable: true,
  51472. configurable: true
  51473. });
  51474. Object.defineProperty(ValueCondition, "IsLesser", {
  51475. /**
  51476. * Returns the number for IsLesser
  51477. */
  51478. get: function () {
  51479. return ValueCondition._IsLesser;
  51480. },
  51481. enumerable: true,
  51482. configurable: true
  51483. });
  51484. /**
  51485. * Compares the given value with the property value for the specified conditional operator
  51486. * @returns the result of the comparison
  51487. */
  51488. ValueCondition.prototype.isValid = function () {
  51489. switch (this.operator) {
  51490. case ValueCondition.IsGreater:
  51491. return this._effectiveTarget[this._property] > this.value;
  51492. case ValueCondition.IsLesser:
  51493. return this._effectiveTarget[this._property] < this.value;
  51494. case ValueCondition.IsEqual:
  51495. case ValueCondition.IsDifferent:
  51496. var check;
  51497. if (this.value.equals) {
  51498. check = this.value.equals(this._effectiveTarget[this._property]);
  51499. }
  51500. else {
  51501. check = this.value === this._effectiveTarget[this._property];
  51502. }
  51503. return this.operator === ValueCondition.IsEqual ? check : !check;
  51504. }
  51505. return false;
  51506. };
  51507. /**
  51508. * Serialize the ValueCondition into a JSON compatible object
  51509. * @returns serialization object
  51510. */
  51511. ValueCondition.prototype.serialize = function () {
  51512. return this._serialize({
  51513. name: "ValueCondition",
  51514. properties: [
  51515. BABYLON.Action._GetTargetProperty(this._target),
  51516. { name: "propertyPath", value: this.propertyPath },
  51517. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51518. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51519. ]
  51520. });
  51521. };
  51522. /**
  51523. * Gets the name of the conditional operator for the ValueCondition
  51524. * @param operator the conditional operator
  51525. * @returns the name
  51526. */
  51527. ValueCondition.GetOperatorName = function (operator) {
  51528. switch (operator) {
  51529. case ValueCondition._IsEqual: return "IsEqual";
  51530. case ValueCondition._IsDifferent: return "IsDifferent";
  51531. case ValueCondition._IsGreater: return "IsGreater";
  51532. case ValueCondition._IsLesser: return "IsLesser";
  51533. default: return "";
  51534. }
  51535. };
  51536. /**
  51537. * Internal only
  51538. * @hidden
  51539. */
  51540. ValueCondition._IsEqual = 0;
  51541. /**
  51542. * Internal only
  51543. * @hidden
  51544. */
  51545. ValueCondition._IsDifferent = 1;
  51546. /**
  51547. * Internal only
  51548. * @hidden
  51549. */
  51550. ValueCondition._IsGreater = 2;
  51551. /**
  51552. * Internal only
  51553. * @hidden
  51554. */
  51555. ValueCondition._IsLesser = 3;
  51556. return ValueCondition;
  51557. }(Condition));
  51558. BABYLON.ValueCondition = ValueCondition;
  51559. /**
  51560. * Defines a predicate condition as an extension of Condition
  51561. */
  51562. var PredicateCondition = /** @class */ (function (_super) {
  51563. __extends(PredicateCondition, _super);
  51564. /**
  51565. * Creates a new PredicateCondition
  51566. * @param actionManager manager for the action the condition applies to
  51567. * @param predicate defines the predicate function used to validate the condition
  51568. */
  51569. function PredicateCondition(actionManager,
  51570. /** defines the predicate function used to validate the condition */
  51571. predicate) {
  51572. var _this = _super.call(this, actionManager) || this;
  51573. _this.predicate = predicate;
  51574. return _this;
  51575. }
  51576. /**
  51577. * @returns the validity of the predicate condition
  51578. */
  51579. PredicateCondition.prototype.isValid = function () {
  51580. return this.predicate();
  51581. };
  51582. return PredicateCondition;
  51583. }(Condition));
  51584. BABYLON.PredicateCondition = PredicateCondition;
  51585. /**
  51586. * Defines a state condition as an extension of Condition
  51587. */
  51588. var StateCondition = /** @class */ (function (_super) {
  51589. __extends(StateCondition, _super);
  51590. /**
  51591. * Creates a new StateCondition
  51592. * @param actionManager manager for the action the condition applies to
  51593. * @param target of the condition
  51594. * @param value to compare with target state
  51595. */
  51596. function StateCondition(actionManager, target, value) {
  51597. var _this = _super.call(this, actionManager) || this;
  51598. _this.value = value;
  51599. _this._target = target;
  51600. return _this;
  51601. }
  51602. /**
  51603. * @returns the validity of the state
  51604. */
  51605. StateCondition.prototype.isValid = function () {
  51606. return this._target.state === this.value;
  51607. };
  51608. /**
  51609. * Serialize the StateCondition into a JSON compatible object
  51610. * @returns serialization object
  51611. */
  51612. StateCondition.prototype.serialize = function () {
  51613. return this._serialize({
  51614. name: "StateCondition",
  51615. properties: [
  51616. BABYLON.Action._GetTargetProperty(this._target),
  51617. { name: "value", value: this.value }
  51618. ]
  51619. });
  51620. };
  51621. return StateCondition;
  51622. }(Condition));
  51623. BABYLON.StateCondition = StateCondition;
  51624. })(BABYLON || (BABYLON = {}));
  51625. //# sourceMappingURL=babylon.condition.js.map
  51626. var BABYLON;
  51627. (function (BABYLON) {
  51628. /**
  51629. * The action to be carried out following a trigger
  51630. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51631. */
  51632. var Action = /** @class */ (function () {
  51633. /**
  51634. * Creates a new Action
  51635. * @param triggerOptions the trigger, with or without parameters, for the action
  51636. * @param condition an optional determinant of action
  51637. */
  51638. function Action(
  51639. /** the trigger, with or without parameters, for the action */
  51640. triggerOptions, condition) {
  51641. this.triggerOptions = triggerOptions;
  51642. /**
  51643. * An event triggered prior to action being executed.
  51644. */
  51645. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51646. if (triggerOptions.parameter) {
  51647. this.trigger = triggerOptions.trigger;
  51648. this._triggerParameter = triggerOptions.parameter;
  51649. }
  51650. else {
  51651. this.trigger = triggerOptions;
  51652. }
  51653. this._nextActiveAction = this;
  51654. this._condition = condition;
  51655. }
  51656. /**
  51657. * Internal only
  51658. * @hidden
  51659. */
  51660. Action.prototype._prepare = function () {
  51661. };
  51662. /**
  51663. * Gets the trigger parameters
  51664. * @returns the trigger parameters
  51665. */
  51666. Action.prototype.getTriggerParameter = function () {
  51667. return this._triggerParameter;
  51668. };
  51669. /**
  51670. * Internal only - executes current action event
  51671. * @hidden
  51672. */
  51673. Action.prototype._executeCurrent = function (evt) {
  51674. if (this._nextActiveAction._condition) {
  51675. var condition = this._nextActiveAction._condition;
  51676. var currentRenderId = this._actionManager.getScene().getRenderId();
  51677. // We cache the current evaluation for the current frame
  51678. if (condition._evaluationId === currentRenderId) {
  51679. if (!condition._currentResult) {
  51680. return;
  51681. }
  51682. }
  51683. else {
  51684. condition._evaluationId = currentRenderId;
  51685. if (!condition.isValid()) {
  51686. condition._currentResult = false;
  51687. return;
  51688. }
  51689. condition._currentResult = true;
  51690. }
  51691. }
  51692. this.onBeforeExecuteObservable.notifyObservers(this);
  51693. this._nextActiveAction.execute(evt);
  51694. this.skipToNextActiveAction();
  51695. };
  51696. /**
  51697. * Execute placeholder for child classes
  51698. * @param evt optional action event
  51699. */
  51700. Action.prototype.execute = function (evt) {
  51701. };
  51702. /**
  51703. * Skips to next active action
  51704. */
  51705. Action.prototype.skipToNextActiveAction = function () {
  51706. if (this._nextActiveAction._child) {
  51707. if (!this._nextActiveAction._child._actionManager) {
  51708. this._nextActiveAction._child._actionManager = this._actionManager;
  51709. }
  51710. this._nextActiveAction = this._nextActiveAction._child;
  51711. }
  51712. else {
  51713. this._nextActiveAction = this;
  51714. }
  51715. };
  51716. /**
  51717. * Adds action to chain of actions, may be a DoNothingAction
  51718. * @param action defines the next action to execute
  51719. * @returns The action passed in
  51720. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51721. */
  51722. Action.prototype.then = function (action) {
  51723. this._child = action;
  51724. action._actionManager = this._actionManager;
  51725. action._prepare();
  51726. return action;
  51727. };
  51728. /**
  51729. * Internal only
  51730. * @hidden
  51731. */
  51732. Action.prototype._getProperty = function (propertyPath) {
  51733. return this._actionManager._getProperty(propertyPath);
  51734. };
  51735. /**
  51736. * Internal only
  51737. * @hidden
  51738. */
  51739. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51740. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51741. };
  51742. /**
  51743. * Serialize placeholder for child classes
  51744. * @param parent of child
  51745. * @returns the serialized object
  51746. */
  51747. Action.prototype.serialize = function (parent) {
  51748. };
  51749. /**
  51750. * Internal only called by serialize
  51751. * @hidden
  51752. */
  51753. Action.prototype._serialize = function (serializedAction, parent) {
  51754. var serializationObject = {
  51755. type: 1,
  51756. children: [],
  51757. name: serializedAction.name,
  51758. properties: serializedAction.properties || []
  51759. };
  51760. // Serialize child
  51761. if (this._child) {
  51762. this._child.serialize(serializationObject);
  51763. }
  51764. // Check if "this" has a condition
  51765. if (this._condition) {
  51766. var serializedCondition = this._condition.serialize();
  51767. serializedCondition.children.push(serializationObject);
  51768. if (parent) {
  51769. parent.children.push(serializedCondition);
  51770. }
  51771. return serializedCondition;
  51772. }
  51773. if (parent) {
  51774. parent.children.push(serializationObject);
  51775. }
  51776. return serializationObject;
  51777. };
  51778. /**
  51779. * Internal only
  51780. * @hidden
  51781. */
  51782. Action._SerializeValueAsString = function (value) {
  51783. if (typeof value === "number") {
  51784. return value.toString();
  51785. }
  51786. if (typeof value === "boolean") {
  51787. return value ? "true" : "false";
  51788. }
  51789. if (value instanceof BABYLON.Vector2) {
  51790. return value.x + ", " + value.y;
  51791. }
  51792. if (value instanceof BABYLON.Vector3) {
  51793. return value.x + ", " + value.y + ", " + value.z;
  51794. }
  51795. if (value instanceof BABYLON.Color3) {
  51796. return value.r + ", " + value.g + ", " + value.b;
  51797. }
  51798. if (value instanceof BABYLON.Color4) {
  51799. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51800. }
  51801. return value; // string
  51802. };
  51803. /**
  51804. * Internal only
  51805. * @hidden
  51806. */
  51807. Action._GetTargetProperty = function (target) {
  51808. return {
  51809. name: "target",
  51810. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51811. : target instanceof BABYLON.Light ? "LightProperties"
  51812. : target instanceof BABYLON.Camera ? "CameraProperties"
  51813. : "SceneProperties",
  51814. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51815. };
  51816. };
  51817. return Action;
  51818. }());
  51819. BABYLON.Action = Action;
  51820. })(BABYLON || (BABYLON = {}));
  51821. //# sourceMappingURL=babylon.action.js.map
  51822. var BABYLON;
  51823. (function (BABYLON) {
  51824. /**
  51825. * ActionEvent is the event being sent when an action is triggered.
  51826. */
  51827. var ActionEvent = /** @class */ (function () {
  51828. /**
  51829. * Creates a new ActionEvent
  51830. * @param source The mesh or sprite that triggered the action
  51831. * @param pointerX The X mouse cursor position at the time of the event
  51832. * @param pointerY The Y mouse cursor position at the time of the event
  51833. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51834. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51835. * @param additionalData additional data for the event
  51836. */
  51837. function ActionEvent(
  51838. /** The mesh or sprite that triggered the action */
  51839. source,
  51840. /** The X mouse cursor position at the time of the event */
  51841. pointerX,
  51842. /** The Y mouse cursor position at the time of the event */
  51843. pointerY,
  51844. /** The mesh that is currently pointed at (can be null) */
  51845. meshUnderPointer,
  51846. /** the original (browser) event that triggered the ActionEvent */
  51847. sourceEvent,
  51848. /** additional data for the event */
  51849. additionalData) {
  51850. this.source = source;
  51851. this.pointerX = pointerX;
  51852. this.pointerY = pointerY;
  51853. this.meshUnderPointer = meshUnderPointer;
  51854. this.sourceEvent = sourceEvent;
  51855. this.additionalData = additionalData;
  51856. }
  51857. /**
  51858. * Helper function to auto-create an ActionEvent from a source mesh.
  51859. * @param source The source mesh that triggered the event
  51860. * @param evt The original (browser) event
  51861. * @param additionalData additional data for the event
  51862. * @returns the new ActionEvent
  51863. */
  51864. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51865. var scene = source.getScene();
  51866. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51867. };
  51868. /**
  51869. * Helper function to auto-create an ActionEvent from a source sprite
  51870. * @param source The source sprite that triggered the event
  51871. * @param scene Scene associated with the sprite
  51872. * @param evt The original (browser) event
  51873. * @param additionalData additional data for the event
  51874. * @returns the new ActionEvent
  51875. */
  51876. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51877. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51878. };
  51879. /**
  51880. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51881. * @param scene the scene where the event occurred
  51882. * @param evt The original (browser) event
  51883. * @returns the new ActionEvent
  51884. */
  51885. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51886. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51887. };
  51888. /**
  51889. * Helper function to auto-create an ActionEvent from a primitive
  51890. * @param prim defines the target primitive
  51891. * @param pointerPos defines the pointer position
  51892. * @param evt The original (browser) event
  51893. * @param additionalData additional data for the event
  51894. * @returns the new ActionEvent
  51895. */
  51896. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51897. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51898. };
  51899. return ActionEvent;
  51900. }());
  51901. BABYLON.ActionEvent = ActionEvent;
  51902. /**
  51903. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51904. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51905. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  51906. */
  51907. var ActionManager = /** @class */ (function () {
  51908. /**
  51909. * Creates a new action manager
  51910. * @param scene defines the hosting scene
  51911. */
  51912. function ActionManager(scene) {
  51913. // Members
  51914. /** Gets the list of actions */
  51915. this.actions = new Array();
  51916. /** Gets the cursor to use when hovering items */
  51917. this.hoverCursor = '';
  51918. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51919. scene.actionManagers.push(this);
  51920. }
  51921. Object.defineProperty(ActionManager, "NothingTrigger", {
  51922. /**
  51923. * Nothing
  51924. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51925. */
  51926. get: function () {
  51927. return ActionManager._NothingTrigger;
  51928. },
  51929. enumerable: true,
  51930. configurable: true
  51931. });
  51932. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51933. /**
  51934. * On pick
  51935. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51936. */
  51937. get: function () {
  51938. return ActionManager._OnPickTrigger;
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51944. /**
  51945. * On left pick
  51946. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51947. */
  51948. get: function () {
  51949. return ActionManager._OnLeftPickTrigger;
  51950. },
  51951. enumerable: true,
  51952. configurable: true
  51953. });
  51954. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51955. /**
  51956. * On right pick
  51957. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51958. */
  51959. get: function () {
  51960. return ActionManager._OnRightPickTrigger;
  51961. },
  51962. enumerable: true,
  51963. configurable: true
  51964. });
  51965. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51966. /**
  51967. * On center pick
  51968. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51969. */
  51970. get: function () {
  51971. return ActionManager._OnCenterPickTrigger;
  51972. },
  51973. enumerable: true,
  51974. configurable: true
  51975. });
  51976. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51977. /**
  51978. * On pick down
  51979. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51980. */
  51981. get: function () {
  51982. return ActionManager._OnPickDownTrigger;
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  51988. /**
  51989. * On double pick
  51990. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51991. */
  51992. get: function () {
  51993. return ActionManager._OnDoublePickTrigger;
  51994. },
  51995. enumerable: true,
  51996. configurable: true
  51997. });
  51998. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  51999. /**
  52000. * On pick up
  52001. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52002. */
  52003. get: function () {
  52004. return ActionManager._OnPickUpTrigger;
  52005. },
  52006. enumerable: true,
  52007. configurable: true
  52008. });
  52009. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52010. /**
  52011. * On pick out.
  52012. * This trigger will only be raised if you also declared a OnPickDown
  52013. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52014. */
  52015. get: function () {
  52016. return ActionManager._OnPickOutTrigger;
  52017. },
  52018. enumerable: true,
  52019. configurable: true
  52020. });
  52021. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52022. /**
  52023. * On long press
  52024. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52025. */
  52026. get: function () {
  52027. return ActionManager._OnLongPressTrigger;
  52028. },
  52029. enumerable: true,
  52030. configurable: true
  52031. });
  52032. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52033. /**
  52034. * On pointer over
  52035. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52036. */
  52037. get: function () {
  52038. return ActionManager._OnPointerOverTrigger;
  52039. },
  52040. enumerable: true,
  52041. configurable: true
  52042. });
  52043. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52044. /**
  52045. * On pointer out
  52046. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52047. */
  52048. get: function () {
  52049. return ActionManager._OnPointerOutTrigger;
  52050. },
  52051. enumerable: true,
  52052. configurable: true
  52053. });
  52054. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52055. /**
  52056. * On every frame
  52057. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52058. */
  52059. get: function () {
  52060. return ActionManager._OnEveryFrameTrigger;
  52061. },
  52062. enumerable: true,
  52063. configurable: true
  52064. });
  52065. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52066. /**
  52067. * On intersection enter
  52068. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52069. */
  52070. get: function () {
  52071. return ActionManager._OnIntersectionEnterTrigger;
  52072. },
  52073. enumerable: true,
  52074. configurable: true
  52075. });
  52076. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52077. /**
  52078. * On intersection exit
  52079. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52080. */
  52081. get: function () {
  52082. return ActionManager._OnIntersectionExitTrigger;
  52083. },
  52084. enumerable: true,
  52085. configurable: true
  52086. });
  52087. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52088. /**
  52089. * On key down
  52090. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52091. */
  52092. get: function () {
  52093. return ActionManager._OnKeyDownTrigger;
  52094. },
  52095. enumerable: true,
  52096. configurable: true
  52097. });
  52098. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52099. /**
  52100. * On key up
  52101. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52102. */
  52103. get: function () {
  52104. return ActionManager._OnKeyUpTrigger;
  52105. },
  52106. enumerable: true,
  52107. configurable: true
  52108. });
  52109. // Methods
  52110. /**
  52111. * Releases all associated resources
  52112. */
  52113. ActionManager.prototype.dispose = function () {
  52114. var index = this._scene.actionManagers.indexOf(this);
  52115. for (var i = 0; i < this.actions.length; i++) {
  52116. var action = this.actions[i];
  52117. ActionManager.Triggers[action.trigger]--;
  52118. if (ActionManager.Triggers[action.trigger] === 0) {
  52119. delete ActionManager.Triggers[action.trigger];
  52120. }
  52121. }
  52122. if (index > -1) {
  52123. this._scene.actionManagers.splice(index, 1);
  52124. }
  52125. };
  52126. /**
  52127. * Gets hosting scene
  52128. * @returns the hosting scene
  52129. */
  52130. ActionManager.prototype.getScene = function () {
  52131. return this._scene;
  52132. };
  52133. /**
  52134. * Does this action manager handles actions of any of the given triggers
  52135. * @param triggers defines the triggers to be tested
  52136. * @return a boolean indicating whether one (or more) of the triggers is handled
  52137. */
  52138. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52139. for (var index = 0; index < this.actions.length; index++) {
  52140. var action = this.actions[index];
  52141. if (triggers.indexOf(action.trigger) > -1) {
  52142. return true;
  52143. }
  52144. }
  52145. return false;
  52146. };
  52147. /**
  52148. * Does this action manager handles actions of a given trigger
  52149. * @param trigger defines the trigger to be tested
  52150. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52151. * @return whether the trigger is handled
  52152. */
  52153. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52154. for (var index = 0; index < this.actions.length; index++) {
  52155. var action = this.actions[index];
  52156. if (action.trigger === trigger) {
  52157. if (parameterPredicate) {
  52158. if (parameterPredicate(action.getTriggerParameter())) {
  52159. return true;
  52160. }
  52161. }
  52162. else {
  52163. return true;
  52164. }
  52165. }
  52166. }
  52167. return false;
  52168. };
  52169. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52170. /**
  52171. * Does this action manager has pointer triggers
  52172. */
  52173. get: function () {
  52174. for (var index = 0; index < this.actions.length; index++) {
  52175. var action = this.actions[index];
  52176. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52177. return true;
  52178. }
  52179. }
  52180. return false;
  52181. },
  52182. enumerable: true,
  52183. configurable: true
  52184. });
  52185. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52186. /**
  52187. * Does this action manager has pick triggers
  52188. */
  52189. get: function () {
  52190. for (var index = 0; index < this.actions.length; index++) {
  52191. var action = this.actions[index];
  52192. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52193. return true;
  52194. }
  52195. }
  52196. return false;
  52197. },
  52198. enumerable: true,
  52199. configurable: true
  52200. });
  52201. Object.defineProperty(ActionManager, "HasTriggers", {
  52202. /**
  52203. * Does exist one action manager with at least one trigger
  52204. **/
  52205. get: function () {
  52206. for (var t in ActionManager.Triggers) {
  52207. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52208. return true;
  52209. }
  52210. }
  52211. return false;
  52212. },
  52213. enumerable: true,
  52214. configurable: true
  52215. });
  52216. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52217. /**
  52218. * Does exist one action manager with at least one pick trigger
  52219. **/
  52220. get: function () {
  52221. for (var t in ActionManager.Triggers) {
  52222. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52223. var t_int = parseInt(t);
  52224. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52225. return true;
  52226. }
  52227. }
  52228. }
  52229. return false;
  52230. },
  52231. enumerable: true,
  52232. configurable: true
  52233. });
  52234. /**
  52235. * Does exist one action manager that handles actions of a given trigger
  52236. * @param trigger defines the trigger to be tested
  52237. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52238. **/
  52239. ActionManager.HasSpecificTrigger = function (trigger) {
  52240. for (var t in ActionManager.Triggers) {
  52241. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52242. var t_int = parseInt(t);
  52243. if (t_int === trigger) {
  52244. return true;
  52245. }
  52246. }
  52247. }
  52248. return false;
  52249. };
  52250. /**
  52251. * Registers an action to this action manager
  52252. * @param action defines the action to be registered
  52253. * @return the action amended (prepared) after registration
  52254. */
  52255. ActionManager.prototype.registerAction = function (action) {
  52256. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52257. if (this.getScene().actionManager !== this) {
  52258. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52259. return null;
  52260. }
  52261. }
  52262. this.actions.push(action);
  52263. if (ActionManager.Triggers[action.trigger]) {
  52264. ActionManager.Triggers[action.trigger]++;
  52265. }
  52266. else {
  52267. ActionManager.Triggers[action.trigger] = 1;
  52268. }
  52269. action._actionManager = this;
  52270. action._prepare();
  52271. return action;
  52272. };
  52273. /**
  52274. * Unregisters an action to this action manager
  52275. * @param action defines the action to be unregistered
  52276. * @return a boolean indicating whether the action has been unregistered
  52277. */
  52278. ActionManager.prototype.unregisterAction = function (action) {
  52279. var index = this.actions.indexOf(action);
  52280. if (index !== -1) {
  52281. this.actions.splice(index, 1);
  52282. ActionManager.Triggers[action.trigger] -= 1;
  52283. if (ActionManager.Triggers[action.trigger] === 0) {
  52284. delete ActionManager.Triggers[action.trigger];
  52285. }
  52286. delete action._actionManager;
  52287. return true;
  52288. }
  52289. return false;
  52290. };
  52291. /**
  52292. * Process a specific trigger
  52293. * @param trigger defines the trigger to process
  52294. * @param evt defines the event details to be processed
  52295. */
  52296. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52297. for (var index = 0; index < this.actions.length; index++) {
  52298. var action = this.actions[index];
  52299. if (action.trigger === trigger) {
  52300. if (evt) {
  52301. if (trigger === ActionManager.OnKeyUpTrigger
  52302. || trigger === ActionManager.OnKeyDownTrigger) {
  52303. var parameter = action.getTriggerParameter();
  52304. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52305. if (!parameter.toLowerCase) {
  52306. continue;
  52307. }
  52308. var lowerCase = parameter.toLowerCase();
  52309. if (lowerCase !== evt.sourceEvent.key) {
  52310. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52311. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52312. if (actualkey !== lowerCase) {
  52313. continue;
  52314. }
  52315. }
  52316. }
  52317. }
  52318. }
  52319. action._executeCurrent(evt);
  52320. }
  52321. }
  52322. };
  52323. /** @hidden */
  52324. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52325. var properties = propertyPath.split(".");
  52326. for (var index = 0; index < properties.length - 1; index++) {
  52327. target = target[properties[index]];
  52328. }
  52329. return target;
  52330. };
  52331. /** @hidden */
  52332. ActionManager.prototype._getProperty = function (propertyPath) {
  52333. var properties = propertyPath.split(".");
  52334. return properties[properties.length - 1];
  52335. };
  52336. /**
  52337. * Serialize this manager to a JSON object
  52338. * @param name defines the property name to store this manager
  52339. * @returns a JSON representation of this manager
  52340. */
  52341. ActionManager.prototype.serialize = function (name) {
  52342. var root = {
  52343. children: new Array(),
  52344. name: name,
  52345. type: 3,
  52346. properties: new Array() // Empty for root but required
  52347. };
  52348. for (var i = 0; i < this.actions.length; i++) {
  52349. var triggerObject = {
  52350. type: 0,
  52351. children: new Array(),
  52352. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52353. properties: new Array()
  52354. };
  52355. var triggerOptions = this.actions[i].triggerOptions;
  52356. if (triggerOptions && typeof triggerOptions !== "number") {
  52357. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52358. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52359. }
  52360. else {
  52361. var parameter = {};
  52362. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52363. if (triggerOptions.parameter.mesh) {
  52364. parameter._meshId = triggerOptions.parameter.mesh.id;
  52365. }
  52366. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52367. }
  52368. }
  52369. // Serialize child action, recursively
  52370. this.actions[i].serialize(triggerObject);
  52371. // Add serialized trigger
  52372. root.children.push(triggerObject);
  52373. }
  52374. return root;
  52375. };
  52376. /**
  52377. * Creates a new ActionManager from a JSON data
  52378. * @param parsedActions defines the JSON data to read from
  52379. * @param object defines the hosting mesh
  52380. * @param scene defines the hosting scene
  52381. */
  52382. ActionManager.Parse = function (parsedActions, object, scene) {
  52383. var actionManager = new ActionManager(scene);
  52384. if (object === null)
  52385. scene.actionManager = actionManager;
  52386. else
  52387. object.actionManager = actionManager;
  52388. // instanciate a new object
  52389. var instanciate = function (name, params) {
  52390. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52391. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52392. newInstance.constructor.apply(newInstance, params);
  52393. return newInstance;
  52394. };
  52395. var parseParameter = function (name, value, target, propertyPath) {
  52396. if (propertyPath === null) {
  52397. // String, boolean or float
  52398. var floatValue = parseFloat(value);
  52399. if (value === "true" || value === "false")
  52400. return value === "true";
  52401. else
  52402. return isNaN(floatValue) ? value : floatValue;
  52403. }
  52404. var effectiveTarget = propertyPath.split(".");
  52405. var values = value.split(",");
  52406. // Get effective Target
  52407. for (var i = 0; i < effectiveTarget.length; i++) {
  52408. target = target[effectiveTarget[i]];
  52409. }
  52410. // Return appropriate value with its type
  52411. if (typeof (target) === "boolean")
  52412. return values[0] === "true";
  52413. if (typeof (target) === "string")
  52414. return values[0];
  52415. // Parameters with multiple values such as Vector3 etc.
  52416. var split = new Array();
  52417. for (var i = 0; i < values.length; i++)
  52418. split.push(parseFloat(values[i]));
  52419. if (target instanceof BABYLON.Vector3)
  52420. return BABYLON.Vector3.FromArray(split);
  52421. if (target instanceof BABYLON.Vector4)
  52422. return BABYLON.Vector4.FromArray(split);
  52423. if (target instanceof BABYLON.Color3)
  52424. return BABYLON.Color3.FromArray(split);
  52425. if (target instanceof BABYLON.Color4)
  52426. return BABYLON.Color4.FromArray(split);
  52427. return parseFloat(values[0]);
  52428. };
  52429. // traverse graph per trigger
  52430. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52431. if (combineArray === void 0) { combineArray = null; }
  52432. if (parsedAction.detached)
  52433. return;
  52434. var parameters = new Array();
  52435. var target = null;
  52436. var propertyPath = null;
  52437. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52438. // Parameters
  52439. if (parsedAction.type === 2)
  52440. parameters.push(actionManager);
  52441. else
  52442. parameters.push(trigger);
  52443. if (combine) {
  52444. var actions = new Array();
  52445. for (var j = 0; j < parsedAction.combine.length; j++) {
  52446. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52447. }
  52448. parameters.push(actions);
  52449. }
  52450. else {
  52451. for (var i = 0; i < parsedAction.properties.length; i++) {
  52452. var value = parsedAction.properties[i].value;
  52453. var name = parsedAction.properties[i].name;
  52454. var targetType = parsedAction.properties[i].targetType;
  52455. if (name === "target")
  52456. if (targetType !== null && targetType === "SceneProperties")
  52457. value = target = scene;
  52458. else
  52459. value = target = scene.getNodeByName(value);
  52460. else if (name === "parent")
  52461. value = scene.getNodeByName(value);
  52462. else if (name === "sound")
  52463. value = scene.getSoundByName(value);
  52464. else if (name !== "propertyPath") {
  52465. if (parsedAction.type === 2 && name === "operator")
  52466. value = BABYLON.ValueCondition[value];
  52467. else
  52468. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52469. }
  52470. else {
  52471. propertyPath = value;
  52472. }
  52473. parameters.push(value);
  52474. }
  52475. }
  52476. if (combineArray === null) {
  52477. parameters.push(condition);
  52478. }
  52479. else {
  52480. parameters.push(null);
  52481. }
  52482. // If interpolate value action
  52483. if (parsedAction.name === "InterpolateValueAction") {
  52484. var param = parameters[parameters.length - 2];
  52485. parameters[parameters.length - 1] = param;
  52486. parameters[parameters.length - 2] = condition;
  52487. }
  52488. // Action or condition(s) and not CombineAction
  52489. var newAction = instanciate(parsedAction.name, parameters);
  52490. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52491. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52492. if (action)
  52493. action.then(nothing);
  52494. else
  52495. actionManager.registerAction(nothing);
  52496. action = nothing;
  52497. }
  52498. if (combineArray === null) {
  52499. if (newAction instanceof BABYLON.Condition) {
  52500. condition = newAction;
  52501. newAction = action;
  52502. }
  52503. else {
  52504. condition = null;
  52505. if (action)
  52506. action.then(newAction);
  52507. else
  52508. actionManager.registerAction(newAction);
  52509. }
  52510. }
  52511. else {
  52512. combineArray.push(newAction);
  52513. }
  52514. for (var i = 0; i < parsedAction.children.length; i++)
  52515. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52516. };
  52517. // triggers
  52518. for (var i = 0; i < parsedActions.children.length; i++) {
  52519. var triggerParams;
  52520. var trigger = parsedActions.children[i];
  52521. if (trigger.properties.length > 0) {
  52522. var param = trigger.properties[0].value;
  52523. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52524. if (value._meshId) {
  52525. value.mesh = scene.getMeshByID(value._meshId);
  52526. }
  52527. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52528. }
  52529. else
  52530. triggerParams = ActionManager[trigger.name];
  52531. for (var j = 0; j < trigger.children.length; j++) {
  52532. if (!trigger.detached)
  52533. traverse(trigger.children[j], triggerParams, null, null);
  52534. }
  52535. }
  52536. };
  52537. /**
  52538. * Get a trigger name by index
  52539. * @param trigger defines the trigger index
  52540. * @returns a trigger name
  52541. */
  52542. ActionManager.GetTriggerName = function (trigger) {
  52543. switch (trigger) {
  52544. case 0: return "NothingTrigger";
  52545. case 1: return "OnPickTrigger";
  52546. case 2: return "OnLeftPickTrigger";
  52547. case 3: return "OnRightPickTrigger";
  52548. case 4: return "OnCenterPickTrigger";
  52549. case 5: return "OnPickDownTrigger";
  52550. case 6: return "OnPickUpTrigger";
  52551. case 7: return "OnLongPressTrigger";
  52552. case 8: return "OnPointerOverTrigger";
  52553. case 9: return "OnPointerOutTrigger";
  52554. case 10: return "OnEveryFrameTrigger";
  52555. case 11: return "OnIntersectionEnterTrigger";
  52556. case 12: return "OnIntersectionExitTrigger";
  52557. case 13: return "OnKeyDownTrigger";
  52558. case 14: return "OnKeyUpTrigger";
  52559. case 15: return "OnPickOutTrigger";
  52560. default: return "";
  52561. }
  52562. };
  52563. // Statics
  52564. ActionManager._NothingTrigger = 0;
  52565. ActionManager._OnPickTrigger = 1;
  52566. ActionManager._OnLeftPickTrigger = 2;
  52567. ActionManager._OnRightPickTrigger = 3;
  52568. ActionManager._OnCenterPickTrigger = 4;
  52569. ActionManager._OnPickDownTrigger = 5;
  52570. ActionManager._OnDoublePickTrigger = 6;
  52571. ActionManager._OnPickUpTrigger = 7;
  52572. ActionManager._OnLongPressTrigger = 8;
  52573. ActionManager._OnPointerOverTrigger = 9;
  52574. ActionManager._OnPointerOutTrigger = 10;
  52575. ActionManager._OnEveryFrameTrigger = 11;
  52576. ActionManager._OnIntersectionEnterTrigger = 12;
  52577. ActionManager._OnIntersectionExitTrigger = 13;
  52578. ActionManager._OnKeyDownTrigger = 14;
  52579. ActionManager._OnKeyUpTrigger = 15;
  52580. ActionManager._OnPickOutTrigger = 16;
  52581. /** Gets the list of active triggers */
  52582. ActionManager.Triggers = {};
  52583. return ActionManager;
  52584. }());
  52585. BABYLON.ActionManager = ActionManager;
  52586. })(BABYLON || (BABYLON = {}));
  52587. //# sourceMappingURL=babylon.actionManager.js.map
  52588. var BABYLON;
  52589. (function (BABYLON) {
  52590. var InterpolateValueAction = /** @class */ (function (_super) {
  52591. __extends(InterpolateValueAction, _super);
  52592. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52593. if (duration === void 0) { duration = 1000; }
  52594. var _this = _super.call(this, triggerOptions, condition) || this;
  52595. _this.propertyPath = propertyPath;
  52596. _this.value = value;
  52597. _this.duration = duration;
  52598. _this.stopOtherAnimations = stopOtherAnimations;
  52599. _this.onInterpolationDone = onInterpolationDone;
  52600. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52601. _this._target = _this._effectiveTarget = target;
  52602. return _this;
  52603. }
  52604. InterpolateValueAction.prototype._prepare = function () {
  52605. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52606. this._property = this._getProperty(this.propertyPath);
  52607. };
  52608. InterpolateValueAction.prototype.execute = function () {
  52609. var _this = this;
  52610. var scene = this._actionManager.getScene();
  52611. var keys = [
  52612. {
  52613. frame: 0,
  52614. value: this._effectiveTarget[this._property]
  52615. }, {
  52616. frame: 100,
  52617. value: this.value
  52618. }
  52619. ];
  52620. var dataType;
  52621. if (typeof this.value === "number") {
  52622. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52623. }
  52624. else if (this.value instanceof BABYLON.Color3) {
  52625. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52626. }
  52627. else if (this.value instanceof BABYLON.Vector3) {
  52628. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52629. }
  52630. else if (this.value instanceof BABYLON.Matrix) {
  52631. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52632. }
  52633. else if (this.value instanceof BABYLON.Quaternion) {
  52634. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52635. }
  52636. else {
  52637. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52638. return;
  52639. }
  52640. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52641. animation.setKeys(keys);
  52642. if (this.stopOtherAnimations) {
  52643. scene.stopAnimation(this._effectiveTarget);
  52644. }
  52645. var wrapper = function () {
  52646. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52647. if (_this.onInterpolationDone) {
  52648. _this.onInterpolationDone();
  52649. }
  52650. };
  52651. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52652. };
  52653. InterpolateValueAction.prototype.serialize = function (parent) {
  52654. return _super.prototype._serialize.call(this, {
  52655. name: "InterpolateValueAction",
  52656. properties: [
  52657. BABYLON.Action._GetTargetProperty(this._target),
  52658. { name: "propertyPath", value: this.propertyPath },
  52659. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52660. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52661. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52662. ]
  52663. }, parent);
  52664. };
  52665. return InterpolateValueAction;
  52666. }(BABYLON.Action));
  52667. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52668. })(BABYLON || (BABYLON = {}));
  52669. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52670. var BABYLON;
  52671. (function (BABYLON) {
  52672. var SwitchBooleanAction = /** @class */ (function (_super) {
  52673. __extends(SwitchBooleanAction, _super);
  52674. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52675. var _this = _super.call(this, triggerOptions, condition) || this;
  52676. _this.propertyPath = propertyPath;
  52677. _this._target = _this._effectiveTarget = target;
  52678. return _this;
  52679. }
  52680. SwitchBooleanAction.prototype._prepare = function () {
  52681. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52682. this._property = this._getProperty(this.propertyPath);
  52683. };
  52684. SwitchBooleanAction.prototype.execute = function () {
  52685. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52686. };
  52687. SwitchBooleanAction.prototype.serialize = function (parent) {
  52688. return _super.prototype._serialize.call(this, {
  52689. name: "SwitchBooleanAction",
  52690. properties: [
  52691. BABYLON.Action._GetTargetProperty(this._target),
  52692. { name: "propertyPath", value: this.propertyPath }
  52693. ]
  52694. }, parent);
  52695. };
  52696. return SwitchBooleanAction;
  52697. }(BABYLON.Action));
  52698. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52699. var SetStateAction = /** @class */ (function (_super) {
  52700. __extends(SetStateAction, _super);
  52701. function SetStateAction(triggerOptions, target, value, condition) {
  52702. var _this = _super.call(this, triggerOptions, condition) || this;
  52703. _this.value = value;
  52704. _this._target = target;
  52705. return _this;
  52706. }
  52707. SetStateAction.prototype.execute = function () {
  52708. this._target.state = this.value;
  52709. };
  52710. SetStateAction.prototype.serialize = function (parent) {
  52711. return _super.prototype._serialize.call(this, {
  52712. name: "SetStateAction",
  52713. properties: [
  52714. BABYLON.Action._GetTargetProperty(this._target),
  52715. { name: "value", value: this.value }
  52716. ]
  52717. }, parent);
  52718. };
  52719. return SetStateAction;
  52720. }(BABYLON.Action));
  52721. BABYLON.SetStateAction = SetStateAction;
  52722. var SetValueAction = /** @class */ (function (_super) {
  52723. __extends(SetValueAction, _super);
  52724. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52725. var _this = _super.call(this, triggerOptions, condition) || this;
  52726. _this.propertyPath = propertyPath;
  52727. _this.value = value;
  52728. _this._target = _this._effectiveTarget = target;
  52729. return _this;
  52730. }
  52731. SetValueAction.prototype._prepare = function () {
  52732. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52733. this._property = this._getProperty(this.propertyPath);
  52734. };
  52735. SetValueAction.prototype.execute = function () {
  52736. this._effectiveTarget[this._property] = this.value;
  52737. if (this._target.markAsDirty) {
  52738. this._target.markAsDirty(this._property);
  52739. }
  52740. };
  52741. SetValueAction.prototype.serialize = function (parent) {
  52742. return _super.prototype._serialize.call(this, {
  52743. name: "SetValueAction",
  52744. properties: [
  52745. BABYLON.Action._GetTargetProperty(this._target),
  52746. { name: "propertyPath", value: this.propertyPath },
  52747. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52748. ]
  52749. }, parent);
  52750. };
  52751. return SetValueAction;
  52752. }(BABYLON.Action));
  52753. BABYLON.SetValueAction = SetValueAction;
  52754. var IncrementValueAction = /** @class */ (function (_super) {
  52755. __extends(IncrementValueAction, _super);
  52756. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52757. var _this = _super.call(this, triggerOptions, condition) || this;
  52758. _this.propertyPath = propertyPath;
  52759. _this.value = value;
  52760. _this._target = _this._effectiveTarget = target;
  52761. return _this;
  52762. }
  52763. IncrementValueAction.prototype._prepare = function () {
  52764. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52765. this._property = this._getProperty(this.propertyPath);
  52766. if (typeof this._effectiveTarget[this._property] !== "number") {
  52767. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52768. }
  52769. };
  52770. IncrementValueAction.prototype.execute = function () {
  52771. this._effectiveTarget[this._property] += this.value;
  52772. if (this._target.markAsDirty) {
  52773. this._target.markAsDirty(this._property);
  52774. }
  52775. };
  52776. IncrementValueAction.prototype.serialize = function (parent) {
  52777. return _super.prototype._serialize.call(this, {
  52778. name: "IncrementValueAction",
  52779. properties: [
  52780. BABYLON.Action._GetTargetProperty(this._target),
  52781. { name: "propertyPath", value: this.propertyPath },
  52782. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52783. ]
  52784. }, parent);
  52785. };
  52786. return IncrementValueAction;
  52787. }(BABYLON.Action));
  52788. BABYLON.IncrementValueAction = IncrementValueAction;
  52789. var PlayAnimationAction = /** @class */ (function (_super) {
  52790. __extends(PlayAnimationAction, _super);
  52791. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52792. var _this = _super.call(this, triggerOptions, condition) || this;
  52793. _this.from = from;
  52794. _this.to = to;
  52795. _this.loop = loop;
  52796. _this._target = target;
  52797. return _this;
  52798. }
  52799. PlayAnimationAction.prototype._prepare = function () {
  52800. };
  52801. PlayAnimationAction.prototype.execute = function () {
  52802. var scene = this._actionManager.getScene();
  52803. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52804. };
  52805. PlayAnimationAction.prototype.serialize = function (parent) {
  52806. return _super.prototype._serialize.call(this, {
  52807. name: "PlayAnimationAction",
  52808. properties: [
  52809. BABYLON.Action._GetTargetProperty(this._target),
  52810. { name: "from", value: String(this.from) },
  52811. { name: "to", value: String(this.to) },
  52812. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52813. ]
  52814. }, parent);
  52815. };
  52816. return PlayAnimationAction;
  52817. }(BABYLON.Action));
  52818. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52819. var StopAnimationAction = /** @class */ (function (_super) {
  52820. __extends(StopAnimationAction, _super);
  52821. function StopAnimationAction(triggerOptions, target, condition) {
  52822. var _this = _super.call(this, triggerOptions, condition) || this;
  52823. _this._target = target;
  52824. return _this;
  52825. }
  52826. StopAnimationAction.prototype._prepare = function () {
  52827. };
  52828. StopAnimationAction.prototype.execute = function () {
  52829. var scene = this._actionManager.getScene();
  52830. scene.stopAnimation(this._target);
  52831. };
  52832. StopAnimationAction.prototype.serialize = function (parent) {
  52833. return _super.prototype._serialize.call(this, {
  52834. name: "StopAnimationAction",
  52835. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52836. }, parent);
  52837. };
  52838. return StopAnimationAction;
  52839. }(BABYLON.Action));
  52840. BABYLON.StopAnimationAction = StopAnimationAction;
  52841. var DoNothingAction = /** @class */ (function (_super) {
  52842. __extends(DoNothingAction, _super);
  52843. function DoNothingAction(triggerOptions, condition) {
  52844. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52845. return _super.call(this, triggerOptions, condition) || this;
  52846. }
  52847. DoNothingAction.prototype.execute = function () {
  52848. };
  52849. DoNothingAction.prototype.serialize = function (parent) {
  52850. return _super.prototype._serialize.call(this, {
  52851. name: "DoNothingAction",
  52852. properties: []
  52853. }, parent);
  52854. };
  52855. return DoNothingAction;
  52856. }(BABYLON.Action));
  52857. BABYLON.DoNothingAction = DoNothingAction;
  52858. var CombineAction = /** @class */ (function (_super) {
  52859. __extends(CombineAction, _super);
  52860. function CombineAction(triggerOptions, children, condition) {
  52861. var _this = _super.call(this, triggerOptions, condition) || this;
  52862. _this.children = children;
  52863. return _this;
  52864. }
  52865. CombineAction.prototype._prepare = function () {
  52866. for (var index = 0; index < this.children.length; index++) {
  52867. this.children[index]._actionManager = this._actionManager;
  52868. this.children[index]._prepare();
  52869. }
  52870. };
  52871. CombineAction.prototype.execute = function (evt) {
  52872. for (var index = 0; index < this.children.length; index++) {
  52873. this.children[index].execute(evt);
  52874. }
  52875. };
  52876. CombineAction.prototype.serialize = function (parent) {
  52877. var serializationObject = _super.prototype._serialize.call(this, {
  52878. name: "CombineAction",
  52879. properties: [],
  52880. combine: []
  52881. }, parent);
  52882. for (var i = 0; i < this.children.length; i++) {
  52883. serializationObject.combine.push(this.children[i].serialize(null));
  52884. }
  52885. return serializationObject;
  52886. };
  52887. return CombineAction;
  52888. }(BABYLON.Action));
  52889. BABYLON.CombineAction = CombineAction;
  52890. var ExecuteCodeAction = /** @class */ (function (_super) {
  52891. __extends(ExecuteCodeAction, _super);
  52892. function ExecuteCodeAction(triggerOptions, func, condition) {
  52893. var _this = _super.call(this, triggerOptions, condition) || this;
  52894. _this.func = func;
  52895. return _this;
  52896. }
  52897. ExecuteCodeAction.prototype.execute = function (evt) {
  52898. this.func(evt);
  52899. };
  52900. return ExecuteCodeAction;
  52901. }(BABYLON.Action));
  52902. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52903. var SetParentAction = /** @class */ (function (_super) {
  52904. __extends(SetParentAction, _super);
  52905. function SetParentAction(triggerOptions, target, parent, condition) {
  52906. var _this = _super.call(this, triggerOptions, condition) || this;
  52907. _this._target = target;
  52908. _this._parent = parent;
  52909. return _this;
  52910. }
  52911. SetParentAction.prototype._prepare = function () {
  52912. };
  52913. SetParentAction.prototype.execute = function () {
  52914. if (this._target.parent === this._parent) {
  52915. return;
  52916. }
  52917. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52918. invertParentWorldMatrix.invert();
  52919. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52920. this._target.parent = this._parent;
  52921. };
  52922. SetParentAction.prototype.serialize = function (parent) {
  52923. return _super.prototype._serialize.call(this, {
  52924. name: "SetParentAction",
  52925. properties: [
  52926. BABYLON.Action._GetTargetProperty(this._target),
  52927. BABYLON.Action._GetTargetProperty(this._parent),
  52928. ]
  52929. }, parent);
  52930. };
  52931. return SetParentAction;
  52932. }(BABYLON.Action));
  52933. BABYLON.SetParentAction = SetParentAction;
  52934. var PlaySoundAction = /** @class */ (function (_super) {
  52935. __extends(PlaySoundAction, _super);
  52936. function PlaySoundAction(triggerOptions, sound, condition) {
  52937. var _this = _super.call(this, triggerOptions, condition) || this;
  52938. _this._sound = sound;
  52939. return _this;
  52940. }
  52941. PlaySoundAction.prototype._prepare = function () {
  52942. };
  52943. PlaySoundAction.prototype.execute = function () {
  52944. if (this._sound !== undefined)
  52945. this._sound.play();
  52946. };
  52947. PlaySoundAction.prototype.serialize = function (parent) {
  52948. return _super.prototype._serialize.call(this, {
  52949. name: "PlaySoundAction",
  52950. properties: [{ name: "sound", value: this._sound.name }]
  52951. }, parent);
  52952. };
  52953. return PlaySoundAction;
  52954. }(BABYLON.Action));
  52955. BABYLON.PlaySoundAction = PlaySoundAction;
  52956. var StopSoundAction = /** @class */ (function (_super) {
  52957. __extends(StopSoundAction, _super);
  52958. function StopSoundAction(triggerOptions, sound, condition) {
  52959. var _this = _super.call(this, triggerOptions, condition) || this;
  52960. _this._sound = sound;
  52961. return _this;
  52962. }
  52963. StopSoundAction.prototype._prepare = function () {
  52964. };
  52965. StopSoundAction.prototype.execute = function () {
  52966. if (this._sound !== undefined)
  52967. this._sound.stop();
  52968. };
  52969. StopSoundAction.prototype.serialize = function (parent) {
  52970. return _super.prototype._serialize.call(this, {
  52971. name: "StopSoundAction",
  52972. properties: [{ name: "sound", value: this._sound.name }]
  52973. }, parent);
  52974. };
  52975. return StopSoundAction;
  52976. }(BABYLON.Action));
  52977. BABYLON.StopSoundAction = StopSoundAction;
  52978. })(BABYLON || (BABYLON = {}));
  52979. //# sourceMappingURL=babylon.directActions.js.map
  52980. var BABYLON;
  52981. (function (BABYLON) {
  52982. var SpriteManager = /** @class */ (function () {
  52983. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  52984. if (epsilon === void 0) { epsilon = 0.01; }
  52985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52986. this.name = name;
  52987. this.sprites = new Array();
  52988. this.renderingGroupId = 0;
  52989. this.layerMask = 0x0FFFFFFF;
  52990. this.fogEnabled = true;
  52991. this.isPickable = false;
  52992. /**
  52993. * An event triggered when the manager is disposed.
  52994. */
  52995. this.onDisposeObservable = new BABYLON.Observable();
  52996. this._vertexBuffers = {};
  52997. this._capacity = capacity;
  52998. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  52999. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53000. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53001. if (cellSize.width && cellSize.height) {
  53002. this.cellWidth = cellSize.width;
  53003. this.cellHeight = cellSize.height;
  53004. }
  53005. else if (cellSize !== undefined) {
  53006. this.cellWidth = cellSize;
  53007. this.cellHeight = cellSize;
  53008. }
  53009. else {
  53010. return;
  53011. }
  53012. this._epsilon = epsilon;
  53013. this._scene = scene;
  53014. this._scene.spriteManagers.push(this);
  53015. var indices = [];
  53016. var index = 0;
  53017. for (var count = 0; count < capacity; count++) {
  53018. indices.push(index);
  53019. indices.push(index + 1);
  53020. indices.push(index + 2);
  53021. indices.push(index);
  53022. indices.push(index + 2);
  53023. indices.push(index + 3);
  53024. index += 4;
  53025. }
  53026. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53027. // VBO
  53028. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53029. this._vertexData = new Float32Array(capacity * 16 * 4);
  53030. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53031. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53032. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53033. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53034. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53035. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53036. this._vertexBuffers["options"] = options;
  53037. this._vertexBuffers["cellInfo"] = cellInfo;
  53038. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53039. // Effects
  53040. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53041. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53042. }
  53043. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53044. set: function (callback) {
  53045. if (this._onDisposeObserver) {
  53046. this.onDisposeObservable.remove(this._onDisposeObserver);
  53047. }
  53048. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53049. },
  53050. enumerable: true,
  53051. configurable: true
  53052. });
  53053. Object.defineProperty(SpriteManager.prototype, "texture", {
  53054. get: function () {
  53055. return this._spriteTexture;
  53056. },
  53057. set: function (value) {
  53058. this._spriteTexture = value;
  53059. },
  53060. enumerable: true,
  53061. configurable: true
  53062. });
  53063. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53064. var arrayOffset = index * 16;
  53065. if (offsetX === 0)
  53066. offsetX = this._epsilon;
  53067. else if (offsetX === 1)
  53068. offsetX = 1 - this._epsilon;
  53069. if (offsetY === 0)
  53070. offsetY = this._epsilon;
  53071. else if (offsetY === 1)
  53072. offsetY = 1 - this._epsilon;
  53073. this._vertexData[arrayOffset] = sprite.position.x;
  53074. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53075. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53076. this._vertexData[arrayOffset + 3] = sprite.angle;
  53077. this._vertexData[arrayOffset + 4] = sprite.width;
  53078. this._vertexData[arrayOffset + 5] = sprite.height;
  53079. this._vertexData[arrayOffset + 6] = offsetX;
  53080. this._vertexData[arrayOffset + 7] = offsetY;
  53081. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53082. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53083. var offset = (sprite.cellIndex / rowSize) >> 0;
  53084. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53085. this._vertexData[arrayOffset + 11] = offset;
  53086. // Color
  53087. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53088. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53089. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53090. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53091. };
  53092. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53093. var count = Math.min(this._capacity, this.sprites.length);
  53094. var min = BABYLON.Vector3.Zero();
  53095. var max = BABYLON.Vector3.Zero();
  53096. var distance = Number.MAX_VALUE;
  53097. var currentSprite = null;
  53098. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53099. var cameraView = camera.getViewMatrix();
  53100. for (var index = 0; index < count; index++) {
  53101. var sprite = this.sprites[index];
  53102. if (!sprite) {
  53103. continue;
  53104. }
  53105. if (predicate) {
  53106. if (!predicate(sprite)) {
  53107. continue;
  53108. }
  53109. }
  53110. else if (!sprite.isPickable) {
  53111. continue;
  53112. }
  53113. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53114. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53115. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53116. if (ray.intersectsBoxMinMax(min, max)) {
  53117. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53118. if (distance > currentDistance) {
  53119. distance = currentDistance;
  53120. currentSprite = sprite;
  53121. if (fastCheck) {
  53122. break;
  53123. }
  53124. }
  53125. }
  53126. }
  53127. if (currentSprite) {
  53128. var result = new BABYLON.PickingInfo();
  53129. result.hit = true;
  53130. result.pickedSprite = currentSprite;
  53131. result.distance = distance;
  53132. return result;
  53133. }
  53134. return null;
  53135. };
  53136. SpriteManager.prototype.render = function () {
  53137. // Check
  53138. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53139. return;
  53140. var engine = this._scene.getEngine();
  53141. var baseSize = this._spriteTexture.getBaseSize();
  53142. // Sprites
  53143. var deltaTime = engine.getDeltaTime();
  53144. var max = Math.min(this._capacity, this.sprites.length);
  53145. var rowSize = baseSize.width / this.cellWidth;
  53146. var offset = 0;
  53147. for (var index = 0; index < max; index++) {
  53148. var sprite = this.sprites[index];
  53149. if (!sprite || !sprite.isVisible) {
  53150. continue;
  53151. }
  53152. sprite._animate(deltaTime);
  53153. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53154. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53155. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53156. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53157. }
  53158. this._buffer.update(this._vertexData);
  53159. // Render
  53160. var effect = this._effectBase;
  53161. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53162. effect = this._effectFog;
  53163. }
  53164. engine.enableEffect(effect);
  53165. var viewMatrix = this._scene.getViewMatrix();
  53166. effect.setTexture("diffuseSampler", this._spriteTexture);
  53167. effect.setMatrix("view", viewMatrix);
  53168. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53169. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53170. // Fog
  53171. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53172. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53173. effect.setColor3("vFogColor", this._scene.fogColor);
  53174. }
  53175. // VBOs
  53176. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53177. // Draw order
  53178. engine.setDepthFunctionToLessOrEqual();
  53179. effect.setBool("alphaTest", true);
  53180. engine.setColorWrite(false);
  53181. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53182. engine.setColorWrite(true);
  53183. effect.setBool("alphaTest", false);
  53184. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53185. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53186. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53187. };
  53188. SpriteManager.prototype.dispose = function () {
  53189. if (this._buffer) {
  53190. this._buffer.dispose();
  53191. this._buffer = null;
  53192. }
  53193. if (this._indexBuffer) {
  53194. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53195. this._indexBuffer = null;
  53196. }
  53197. if (this._spriteTexture) {
  53198. this._spriteTexture.dispose();
  53199. this._spriteTexture = null;
  53200. }
  53201. // Remove from scene
  53202. var index = this._scene.spriteManagers.indexOf(this);
  53203. this._scene.spriteManagers.splice(index, 1);
  53204. // Callback
  53205. this.onDisposeObservable.notifyObservers(this);
  53206. this.onDisposeObservable.clear();
  53207. };
  53208. return SpriteManager;
  53209. }());
  53210. BABYLON.SpriteManager = SpriteManager;
  53211. })(BABYLON || (BABYLON = {}));
  53212. //# sourceMappingURL=babylon.spriteManager.js.map
  53213. var BABYLON;
  53214. (function (BABYLON) {
  53215. var Sprite = /** @class */ (function () {
  53216. function Sprite(name, manager) {
  53217. this.name = name;
  53218. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53219. this.width = 1.0;
  53220. this.height = 1.0;
  53221. this.angle = 0;
  53222. this.cellIndex = 0;
  53223. this.invertU = 0;
  53224. this.invertV = 0;
  53225. this.animations = new Array();
  53226. this.isPickable = false;
  53227. this._animationStarted = false;
  53228. this._loopAnimation = false;
  53229. this._fromIndex = 0;
  53230. this._toIndex = 0;
  53231. this._delay = 0;
  53232. this._direction = 1;
  53233. this._time = 0;
  53234. /**
  53235. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53236. */
  53237. this.isVisible = true;
  53238. this._manager = manager;
  53239. this._manager.sprites.push(this);
  53240. this.position = BABYLON.Vector3.Zero();
  53241. }
  53242. Object.defineProperty(Sprite.prototype, "size", {
  53243. get: function () {
  53244. return this.width;
  53245. },
  53246. set: function (value) {
  53247. this.width = value;
  53248. this.height = value;
  53249. },
  53250. enumerable: true,
  53251. configurable: true
  53252. });
  53253. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53254. this._fromIndex = from;
  53255. this._toIndex = to;
  53256. this._loopAnimation = loop;
  53257. this._delay = delay;
  53258. this._animationStarted = true;
  53259. this._direction = from < to ? 1 : -1;
  53260. this.cellIndex = from;
  53261. this._time = 0;
  53262. this._onAnimationEnd = onAnimationEnd;
  53263. };
  53264. Sprite.prototype.stopAnimation = function () {
  53265. this._animationStarted = false;
  53266. };
  53267. Sprite.prototype._animate = function (deltaTime) {
  53268. if (!this._animationStarted)
  53269. return;
  53270. this._time += deltaTime;
  53271. if (this._time > this._delay) {
  53272. this._time = this._time % this._delay;
  53273. this.cellIndex += this._direction;
  53274. if (this.cellIndex > this._toIndex) {
  53275. if (this._loopAnimation) {
  53276. this.cellIndex = this._fromIndex;
  53277. }
  53278. else {
  53279. this.cellIndex = this._toIndex;
  53280. this._animationStarted = false;
  53281. if (this._onAnimationEnd) {
  53282. this._onAnimationEnd();
  53283. }
  53284. if (this.disposeWhenFinishedAnimating) {
  53285. this.dispose();
  53286. }
  53287. }
  53288. }
  53289. }
  53290. };
  53291. Sprite.prototype.dispose = function () {
  53292. for (var i = 0; i < this._manager.sprites.length; i++) {
  53293. if (this._manager.sprites[i] == this) {
  53294. this._manager.sprites.splice(i, 1);
  53295. }
  53296. }
  53297. };
  53298. return Sprite;
  53299. }());
  53300. BABYLON.Sprite = Sprite;
  53301. })(BABYLON || (BABYLON = {}));
  53302. //# sourceMappingURL=babylon.sprite.js.map
  53303. var BABYLON;
  53304. (function (BABYLON) {
  53305. var IntersectionInfo = /** @class */ (function () {
  53306. function IntersectionInfo(bu, bv, distance) {
  53307. this.bu = bu;
  53308. this.bv = bv;
  53309. this.distance = distance;
  53310. this.faceId = 0;
  53311. this.subMeshId = 0;
  53312. }
  53313. return IntersectionInfo;
  53314. }());
  53315. BABYLON.IntersectionInfo = IntersectionInfo;
  53316. /**
  53317. * Information about the result of picking within a scene
  53318. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53319. */
  53320. var PickingInfo = /** @class */ (function () {
  53321. function PickingInfo() {
  53322. /**
  53323. * If the pick collided with an object
  53324. */
  53325. this.hit = false;
  53326. /**
  53327. * Distance away where the pick collided
  53328. */
  53329. this.distance = 0;
  53330. /**
  53331. * The location of pick collision
  53332. */
  53333. this.pickedPoint = null;
  53334. /**
  53335. * The mesh corrisponding the the pick collision
  53336. */
  53337. this.pickedMesh = null;
  53338. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53339. this.bu = 0;
  53340. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53341. this.bv = 0;
  53342. /** The id of the face on the mesh that was picked */
  53343. this.faceId = -1;
  53344. /** Id of the the submesh that was picked */
  53345. this.subMeshId = 0;
  53346. /** If a sprite was picked, this will be the sprite the pick collided with */
  53347. this.pickedSprite = null;
  53348. /**
  53349. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53350. */
  53351. this.originMesh = null;
  53352. /**
  53353. * The ray that was used to perform the picking.
  53354. */
  53355. this.ray = null;
  53356. }
  53357. /**
  53358. * Gets the normal corrispodning to the face the pick collided with
  53359. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53360. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53361. * @returns The normal corrispodning to the face the pick collided with
  53362. */
  53363. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53364. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53365. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53366. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53367. return null;
  53368. }
  53369. var indices = this.pickedMesh.getIndices();
  53370. if (!indices) {
  53371. return null;
  53372. }
  53373. var result;
  53374. if (useVerticesNormals) {
  53375. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53376. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53377. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53378. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53379. normal0 = normal0.scale(this.bu);
  53380. normal1 = normal1.scale(this.bv);
  53381. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53382. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53383. }
  53384. else {
  53385. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53386. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53387. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53388. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53389. var p1p2 = vertex1.subtract(vertex2);
  53390. var p3p2 = vertex3.subtract(vertex2);
  53391. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53392. }
  53393. if (useWorldCoordinates) {
  53394. var wm = this.pickedMesh.getWorldMatrix();
  53395. if (this.pickedMesh.nonUniformScaling) {
  53396. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53397. wm = BABYLON.Tmp.Matrix[0];
  53398. wm.setTranslationFromFloats(0, 0, 0);
  53399. wm.invert();
  53400. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53401. wm = BABYLON.Tmp.Matrix[1];
  53402. }
  53403. result = BABYLON.Vector3.TransformNormal(result, wm);
  53404. }
  53405. result.normalize();
  53406. return result;
  53407. };
  53408. /**
  53409. * Gets the texture coordinates of where the pick occured
  53410. * @returns the vector containing the coordnates of the texture
  53411. */
  53412. PickingInfo.prototype.getTextureCoordinates = function () {
  53413. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53414. return null;
  53415. }
  53416. var indices = this.pickedMesh.getIndices();
  53417. if (!indices) {
  53418. return null;
  53419. }
  53420. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53421. if (!uvs) {
  53422. return null;
  53423. }
  53424. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53425. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53426. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53427. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53428. uv1 = uv1.scale(this.bu);
  53429. uv2 = uv2.scale(this.bv);
  53430. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53431. };
  53432. return PickingInfo;
  53433. }());
  53434. BABYLON.PickingInfo = PickingInfo;
  53435. })(BABYLON || (BABYLON = {}));
  53436. //# sourceMappingURL=babylon.pickingInfo.js.map
  53437. var BABYLON;
  53438. (function (BABYLON) {
  53439. var Ray = /** @class */ (function () {
  53440. function Ray(origin, direction, length) {
  53441. if (length === void 0) { length = Number.MAX_VALUE; }
  53442. this.origin = origin;
  53443. this.direction = direction;
  53444. this.length = length;
  53445. }
  53446. // Methods
  53447. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53448. var d = 0.0;
  53449. var maxValue = Number.MAX_VALUE;
  53450. var inv;
  53451. var min;
  53452. var max;
  53453. var temp;
  53454. if (Math.abs(this.direction.x) < 0.0000001) {
  53455. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53456. return false;
  53457. }
  53458. }
  53459. else {
  53460. inv = 1.0 / this.direction.x;
  53461. min = (minimum.x - this.origin.x) * inv;
  53462. max = (maximum.x - this.origin.x) * inv;
  53463. if (max === -Infinity) {
  53464. max = Infinity;
  53465. }
  53466. if (min > max) {
  53467. temp = min;
  53468. min = max;
  53469. max = temp;
  53470. }
  53471. d = Math.max(min, d);
  53472. maxValue = Math.min(max, maxValue);
  53473. if (d > maxValue) {
  53474. return false;
  53475. }
  53476. }
  53477. if (Math.abs(this.direction.y) < 0.0000001) {
  53478. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53479. return false;
  53480. }
  53481. }
  53482. else {
  53483. inv = 1.0 / this.direction.y;
  53484. min = (minimum.y - this.origin.y) * inv;
  53485. max = (maximum.y - this.origin.y) * inv;
  53486. if (max === -Infinity) {
  53487. max = Infinity;
  53488. }
  53489. if (min > max) {
  53490. temp = min;
  53491. min = max;
  53492. max = temp;
  53493. }
  53494. d = Math.max(min, d);
  53495. maxValue = Math.min(max, maxValue);
  53496. if (d > maxValue) {
  53497. return false;
  53498. }
  53499. }
  53500. if (Math.abs(this.direction.z) < 0.0000001) {
  53501. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53502. return false;
  53503. }
  53504. }
  53505. else {
  53506. inv = 1.0 / this.direction.z;
  53507. min = (minimum.z - this.origin.z) * inv;
  53508. max = (maximum.z - this.origin.z) * inv;
  53509. if (max === -Infinity) {
  53510. max = Infinity;
  53511. }
  53512. if (min > max) {
  53513. temp = min;
  53514. min = max;
  53515. max = temp;
  53516. }
  53517. d = Math.max(min, d);
  53518. maxValue = Math.min(max, maxValue);
  53519. if (d > maxValue) {
  53520. return false;
  53521. }
  53522. }
  53523. return true;
  53524. };
  53525. Ray.prototype.intersectsBox = function (box) {
  53526. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53527. };
  53528. Ray.prototype.intersectsSphere = function (sphere) {
  53529. var x = sphere.center.x - this.origin.x;
  53530. var y = sphere.center.y - this.origin.y;
  53531. var z = sphere.center.z - this.origin.z;
  53532. var pyth = (x * x) + (y * y) + (z * z);
  53533. var rr = sphere.radius * sphere.radius;
  53534. if (pyth <= rr) {
  53535. return true;
  53536. }
  53537. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53538. if (dot < 0.0) {
  53539. return false;
  53540. }
  53541. var temp = pyth - (dot * dot);
  53542. return temp <= rr;
  53543. };
  53544. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53545. if (!this._edge1) {
  53546. this._edge1 = BABYLON.Vector3.Zero();
  53547. this._edge2 = BABYLON.Vector3.Zero();
  53548. this._pvec = BABYLON.Vector3.Zero();
  53549. this._tvec = BABYLON.Vector3.Zero();
  53550. this._qvec = BABYLON.Vector3.Zero();
  53551. }
  53552. vertex1.subtractToRef(vertex0, this._edge1);
  53553. vertex2.subtractToRef(vertex0, this._edge2);
  53554. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53555. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53556. if (det === 0) {
  53557. return null;
  53558. }
  53559. var invdet = 1 / det;
  53560. this.origin.subtractToRef(vertex0, this._tvec);
  53561. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53562. if (bu < 0 || bu > 1.0) {
  53563. return null;
  53564. }
  53565. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53566. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53567. if (bv < 0 || bu + bv > 1.0) {
  53568. return null;
  53569. }
  53570. //check if the distance is longer than the predefined length.
  53571. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53572. if (distance > this.length) {
  53573. return null;
  53574. }
  53575. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53576. };
  53577. Ray.prototype.intersectsPlane = function (plane) {
  53578. var distance;
  53579. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53580. if (Math.abs(result1) < 9.99999997475243E-07) {
  53581. return null;
  53582. }
  53583. else {
  53584. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53585. distance = (-plane.d - result2) / result1;
  53586. if (distance < 0.0) {
  53587. if (distance < -9.99999997475243E-07) {
  53588. return null;
  53589. }
  53590. else {
  53591. return 0;
  53592. }
  53593. }
  53594. return distance;
  53595. }
  53596. };
  53597. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53598. var tm = BABYLON.Tmp.Matrix[0];
  53599. mesh.getWorldMatrix().invertToRef(tm);
  53600. if (this._tmpRay) {
  53601. Ray.TransformToRef(this, tm, this._tmpRay);
  53602. }
  53603. else {
  53604. this._tmpRay = Ray.Transform(this, tm);
  53605. }
  53606. return mesh.intersects(this._tmpRay, fastCheck);
  53607. };
  53608. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53609. if (results) {
  53610. results.length = 0;
  53611. }
  53612. else {
  53613. results = [];
  53614. }
  53615. for (var i = 0; i < meshes.length; i++) {
  53616. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53617. if (pickInfo.hit) {
  53618. results.push(pickInfo);
  53619. }
  53620. }
  53621. results.sort(this._comparePickingInfo);
  53622. return results;
  53623. };
  53624. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53625. if (pickingInfoA.distance < pickingInfoB.distance) {
  53626. return -1;
  53627. }
  53628. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53629. return 1;
  53630. }
  53631. else {
  53632. return 0;
  53633. }
  53634. };
  53635. /**
  53636. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53637. * @param sega the first point of the segment to test the intersection against
  53638. * @param segb the second point of the segment to test the intersection against
  53639. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53640. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53641. */
  53642. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53643. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53644. var u = segb.subtract(sega);
  53645. var v = rsegb.subtract(this.origin);
  53646. var w = sega.subtract(this.origin);
  53647. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53648. var b = BABYLON.Vector3.Dot(u, v);
  53649. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53650. var d = BABYLON.Vector3.Dot(u, w);
  53651. var e = BABYLON.Vector3.Dot(v, w);
  53652. var D = a * c - b * b; // always >= 0
  53653. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53654. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53655. // compute the line parameters of the two closest points
  53656. if (D < Ray.smallnum) { // the lines are almost parallel
  53657. sN = 0.0; // force using point P0 on segment S1
  53658. sD = 1.0; // to prevent possible division by 0.0 later
  53659. tN = e;
  53660. tD = c;
  53661. }
  53662. else { // get the closest points on the infinite lines
  53663. sN = (b * e - c * d);
  53664. tN = (a * e - b * d);
  53665. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53666. sN = 0.0;
  53667. tN = e;
  53668. tD = c;
  53669. }
  53670. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53671. sN = sD;
  53672. tN = e + b;
  53673. tD = c;
  53674. }
  53675. }
  53676. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53677. tN = 0.0;
  53678. // recompute sc for this edge
  53679. if (-d < 0.0) {
  53680. sN = 0.0;
  53681. }
  53682. else if (-d > a)
  53683. sN = sD;
  53684. else {
  53685. sN = -d;
  53686. sD = a;
  53687. }
  53688. }
  53689. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  53690. tN = tD;
  53691. // recompute sc for this edge
  53692. if ((-d + b) < 0.0) {
  53693. sN = 0;
  53694. }
  53695. else if ((-d + b) > a) {
  53696. sN = sD;
  53697. }
  53698. else {
  53699. sN = (-d + b);
  53700. sD = a;
  53701. }
  53702. }
  53703. // finally do the division to get sc and tc
  53704. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53705. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53706. // get the difference of the two closest points
  53707. var qtc = v.multiplyByFloats(tc, tc, tc);
  53708. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53709. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53710. if (isIntersected) {
  53711. return qtc.length();
  53712. }
  53713. return -1;
  53714. };
  53715. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53716. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53717. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53718. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53719. this.direction.normalize();
  53720. return this;
  53721. };
  53722. // Statics
  53723. Ray.Zero = function () {
  53724. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53725. };
  53726. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53727. var result = Ray.Zero();
  53728. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53729. };
  53730. /**
  53731. * 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
  53732. * transformed to the given world matrix.
  53733. * @param origin The origin point
  53734. * @param end The end point
  53735. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53736. */
  53737. Ray.CreateNewFromTo = function (origin, end, world) {
  53738. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53739. var direction = end.subtract(origin);
  53740. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53741. direction.normalize();
  53742. return Ray.Transform(new Ray(origin, direction, length), world);
  53743. };
  53744. Ray.Transform = function (ray, matrix) {
  53745. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53746. Ray.TransformToRef(ray, matrix, result);
  53747. return result;
  53748. };
  53749. Ray.TransformToRef = function (ray, matrix, result) {
  53750. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53751. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53752. result.length = ray.length;
  53753. var dir = result.direction;
  53754. var len = dir.length();
  53755. if (!(len === 0 || len === 1)) {
  53756. var num = 1.0 / len;
  53757. dir.x *= num;
  53758. dir.y *= num;
  53759. dir.z *= num;
  53760. result.length *= len;
  53761. }
  53762. };
  53763. Ray.smallnum = 0.00000001;
  53764. Ray.rayl = 10e8;
  53765. return Ray;
  53766. }());
  53767. BABYLON.Ray = Ray;
  53768. })(BABYLON || (BABYLON = {}));
  53769. //# sourceMappingURL=babylon.ray.js.map
  53770. var BABYLON;
  53771. (function (BABYLON) {
  53772. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53773. if (boxMin.x > sphereCenter.x + sphereRadius)
  53774. return false;
  53775. if (sphereCenter.x - sphereRadius > boxMax.x)
  53776. return false;
  53777. if (boxMin.y > sphereCenter.y + sphereRadius)
  53778. return false;
  53779. if (sphereCenter.y - sphereRadius > boxMax.y)
  53780. return false;
  53781. if (boxMin.z > sphereCenter.z + sphereRadius)
  53782. return false;
  53783. if (sphereCenter.z - sphereRadius > boxMax.z)
  53784. return false;
  53785. return true;
  53786. };
  53787. var getLowestRoot = (function () {
  53788. var result = { root: 0, found: false };
  53789. return function (a, b, c, maxR) {
  53790. result.root = 0;
  53791. result.found = false;
  53792. var determinant = b * b - 4.0 * a * c;
  53793. if (determinant < 0)
  53794. return result;
  53795. var sqrtD = Math.sqrt(determinant);
  53796. var r1 = (-b - sqrtD) / (2.0 * a);
  53797. var r2 = (-b + sqrtD) / (2.0 * a);
  53798. if (r1 > r2) {
  53799. var temp = r2;
  53800. r2 = r1;
  53801. r1 = temp;
  53802. }
  53803. if (r1 > 0 && r1 < maxR) {
  53804. result.root = r1;
  53805. result.found = true;
  53806. return result;
  53807. }
  53808. if (r2 > 0 && r2 < maxR) {
  53809. result.root = r2;
  53810. result.found = true;
  53811. return result;
  53812. }
  53813. return result;
  53814. };
  53815. })();
  53816. var Collider = /** @class */ (function () {
  53817. function Collider() {
  53818. this._collisionPoint = BABYLON.Vector3.Zero();
  53819. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53820. this._tempVector = BABYLON.Vector3.Zero();
  53821. this._tempVector2 = BABYLON.Vector3.Zero();
  53822. this._tempVector3 = BABYLON.Vector3.Zero();
  53823. this._tempVector4 = BABYLON.Vector3.Zero();
  53824. this._edge = BABYLON.Vector3.Zero();
  53825. this._baseToVertex = BABYLON.Vector3.Zero();
  53826. this._destinationPoint = BABYLON.Vector3.Zero();
  53827. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53828. this._displacementVector = BABYLON.Vector3.Zero();
  53829. this._radius = BABYLON.Vector3.One();
  53830. this._retry = 0;
  53831. this._basePointWorld = BABYLON.Vector3.Zero();
  53832. this._velocityWorld = BABYLON.Vector3.Zero();
  53833. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53834. this._collisionMask = -1;
  53835. }
  53836. Object.defineProperty(Collider.prototype, "collisionMask", {
  53837. get: function () {
  53838. return this._collisionMask;
  53839. },
  53840. set: function (mask) {
  53841. this._collisionMask = !isNaN(mask) ? mask : -1;
  53842. },
  53843. enumerable: true,
  53844. configurable: true
  53845. });
  53846. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53847. /**
  53848. * Gets the plane normal used to compute the sliding response (in local space)
  53849. */
  53850. get: function () {
  53851. return this._slidePlaneNormal;
  53852. },
  53853. enumerable: true,
  53854. configurable: true
  53855. });
  53856. // Methods
  53857. Collider.prototype._initialize = function (source, dir, e) {
  53858. this._velocity = dir;
  53859. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53860. this._basePoint = source;
  53861. source.multiplyToRef(this._radius, this._basePointWorld);
  53862. dir.multiplyToRef(this._radius, this._velocityWorld);
  53863. this._velocityWorldLength = this._velocityWorld.length();
  53864. this._epsilon = e;
  53865. this.collisionFound = false;
  53866. };
  53867. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53868. pa.subtractToRef(point, this._tempVector);
  53869. pb.subtractToRef(point, this._tempVector2);
  53870. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53871. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53872. if (d < 0)
  53873. return false;
  53874. pc.subtractToRef(point, this._tempVector3);
  53875. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53876. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53877. if (d < 0)
  53878. return false;
  53879. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53880. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53881. return d >= 0;
  53882. };
  53883. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53884. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53885. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53886. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53887. return false;
  53888. }
  53889. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53890. return false;
  53891. return true;
  53892. };
  53893. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53894. var t0;
  53895. var embeddedInPlane = false;
  53896. //defensive programming, actually not needed.
  53897. if (!trianglePlaneArray) {
  53898. trianglePlaneArray = [];
  53899. }
  53900. if (!trianglePlaneArray[faceIndex]) {
  53901. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53902. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53903. }
  53904. var trianglePlane = trianglePlaneArray[faceIndex];
  53905. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53906. return;
  53907. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53908. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53909. if (normalDotVelocity == 0) {
  53910. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53911. return;
  53912. embeddedInPlane = true;
  53913. t0 = 0;
  53914. }
  53915. else {
  53916. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53917. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53918. if (t0 > t1) {
  53919. var temp = t1;
  53920. t1 = t0;
  53921. t0 = temp;
  53922. }
  53923. if (t0 > 1.0 || t1 < 0.0)
  53924. return;
  53925. if (t0 < 0)
  53926. t0 = 0;
  53927. if (t0 > 1.0)
  53928. t0 = 1.0;
  53929. }
  53930. this._collisionPoint.copyFromFloats(0, 0, 0);
  53931. var found = false;
  53932. var t = 1.0;
  53933. if (!embeddedInPlane) {
  53934. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53935. this._velocity.scaleToRef(t0, this._tempVector);
  53936. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53937. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53938. found = true;
  53939. t = t0;
  53940. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53941. }
  53942. }
  53943. if (!found) {
  53944. var velocitySquaredLength = this._velocity.lengthSquared();
  53945. var a = velocitySquaredLength;
  53946. this._basePoint.subtractToRef(p1, this._tempVector);
  53947. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53948. var c = this._tempVector.lengthSquared() - 1.0;
  53949. var lowestRoot = getLowestRoot(a, b, c, t);
  53950. if (lowestRoot.found) {
  53951. t = lowestRoot.root;
  53952. found = true;
  53953. this._collisionPoint.copyFrom(p1);
  53954. }
  53955. this._basePoint.subtractToRef(p2, this._tempVector);
  53956. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53957. c = this._tempVector.lengthSquared() - 1.0;
  53958. lowestRoot = getLowestRoot(a, b, c, t);
  53959. if (lowestRoot.found) {
  53960. t = lowestRoot.root;
  53961. found = true;
  53962. this._collisionPoint.copyFrom(p2);
  53963. }
  53964. this._basePoint.subtractToRef(p3, this._tempVector);
  53965. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53966. c = this._tempVector.lengthSquared() - 1.0;
  53967. lowestRoot = getLowestRoot(a, b, c, t);
  53968. if (lowestRoot.found) {
  53969. t = lowestRoot.root;
  53970. found = true;
  53971. this._collisionPoint.copyFrom(p3);
  53972. }
  53973. p2.subtractToRef(p1, this._edge);
  53974. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53975. var edgeSquaredLength = this._edge.lengthSquared();
  53976. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53977. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53978. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53979. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53980. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53981. lowestRoot = getLowestRoot(a, b, c, t);
  53982. if (lowestRoot.found) {
  53983. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53984. if (f >= 0.0 && f <= 1.0) {
  53985. t = lowestRoot.root;
  53986. found = true;
  53987. this._edge.scaleInPlace(f);
  53988. p1.addToRef(this._edge, this._collisionPoint);
  53989. }
  53990. }
  53991. p3.subtractToRef(p2, this._edge);
  53992. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53993. edgeSquaredLength = this._edge.lengthSquared();
  53994. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53995. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53996. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53997. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53998. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53999. lowestRoot = getLowestRoot(a, b, c, t);
  54000. if (lowestRoot.found) {
  54001. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54002. if (f >= 0.0 && f <= 1.0) {
  54003. t = lowestRoot.root;
  54004. found = true;
  54005. this._edge.scaleInPlace(f);
  54006. p2.addToRef(this._edge, this._collisionPoint);
  54007. }
  54008. }
  54009. p1.subtractToRef(p3, this._edge);
  54010. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54011. edgeSquaredLength = this._edge.lengthSquared();
  54012. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54013. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54014. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54015. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54016. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54017. lowestRoot = getLowestRoot(a, b, c, t);
  54018. if (lowestRoot.found) {
  54019. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54020. if (f >= 0.0 && f <= 1.0) {
  54021. t = lowestRoot.root;
  54022. found = true;
  54023. this._edge.scaleInPlace(f);
  54024. p3.addToRef(this._edge, this._collisionPoint);
  54025. }
  54026. }
  54027. }
  54028. if (found) {
  54029. var distToCollision = t * this._velocity.length();
  54030. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54031. if (!this.intersectionPoint) {
  54032. this.intersectionPoint = this._collisionPoint.clone();
  54033. }
  54034. else {
  54035. this.intersectionPoint.copyFrom(this._collisionPoint);
  54036. }
  54037. this._nearestDistance = distToCollision;
  54038. this.collisionFound = true;
  54039. }
  54040. }
  54041. };
  54042. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54043. for (var i = indexStart; i < indexEnd; i += 3) {
  54044. var p1 = pts[indices[i] - decal];
  54045. var p2 = pts[indices[i + 1] - decal];
  54046. var p3 = pts[indices[i + 2] - decal];
  54047. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54048. }
  54049. };
  54050. Collider.prototype._getResponse = function (pos, vel) {
  54051. pos.addToRef(vel, this._destinationPoint);
  54052. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54053. this._basePoint.addToRef(vel, pos);
  54054. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54055. this._slidePlaneNormal.normalize();
  54056. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54057. pos.addInPlace(this._displacementVector);
  54058. this.intersectionPoint.addInPlace(this._displacementVector);
  54059. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54060. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54061. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54062. };
  54063. return Collider;
  54064. }());
  54065. BABYLON.Collider = Collider;
  54066. })(BABYLON || (BABYLON = {}));
  54067. //# sourceMappingURL=babylon.collider.js.map
  54068. var BABYLON;
  54069. (function (BABYLON) {
  54070. //WebWorker code will be inserted to this variable.
  54071. BABYLON.CollisionWorker = "";
  54072. /** Defines supported task for worker process */
  54073. var WorkerTaskType;
  54074. (function (WorkerTaskType) {
  54075. /** Initialization */
  54076. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54077. /** Update of geometry */
  54078. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54079. /** Evaluate collision */
  54080. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54081. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54082. /** Defines kind of replies returned by worker */
  54083. var WorkerReplyType;
  54084. (function (WorkerReplyType) {
  54085. /** Success */
  54086. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54087. /** Unkown error */
  54088. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54089. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54090. var CollisionCoordinatorWorker = /** @class */ (function () {
  54091. function CollisionCoordinatorWorker() {
  54092. var _this = this;
  54093. this._scaledPosition = BABYLON.Vector3.Zero();
  54094. this._scaledVelocity = BABYLON.Vector3.Zero();
  54095. this.onMeshUpdated = function (transformNode) {
  54096. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54097. };
  54098. this.onGeometryUpdated = function (geometry) {
  54099. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54100. };
  54101. this._afterRender = function () {
  54102. if (!_this._init)
  54103. return;
  54104. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54105. return;
  54106. }
  54107. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54108. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54109. if (_this._runningUpdated > 4) {
  54110. return;
  54111. }
  54112. ++_this._runningUpdated;
  54113. var payload = {
  54114. updatedMeshes: _this._addUpdateMeshesList,
  54115. updatedGeometries: _this._addUpdateGeometriesList,
  54116. removedGeometries: _this._toRemoveGeometryArray,
  54117. removedMeshes: _this._toRemoveMeshesArray
  54118. };
  54119. var message = {
  54120. payload: payload,
  54121. taskType: WorkerTaskType.UPDATE
  54122. };
  54123. var serializable = [];
  54124. for (var id in payload.updatedGeometries) {
  54125. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54126. //prepare transferables
  54127. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54128. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54129. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54130. }
  54131. }
  54132. _this._worker.postMessage(message, serializable);
  54133. _this._addUpdateMeshesList = {};
  54134. _this._addUpdateGeometriesList = {};
  54135. _this._toRemoveGeometryArray = [];
  54136. _this._toRemoveMeshesArray = [];
  54137. };
  54138. this._onMessageFromWorker = function (e) {
  54139. var returnData = e.data;
  54140. if (returnData.error != WorkerReplyType.SUCCESS) {
  54141. //TODO what errors can be returned from the worker?
  54142. BABYLON.Tools.Warn("error returned from worker!");
  54143. return;
  54144. }
  54145. switch (returnData.taskType) {
  54146. case WorkerTaskType.INIT:
  54147. _this._init = true;
  54148. //Update the worked with ALL of the scene's current state
  54149. _this._scene.meshes.forEach(function (mesh) {
  54150. _this.onMeshAdded(mesh);
  54151. });
  54152. _this._scene.getGeometries().forEach(function (geometry) {
  54153. _this.onGeometryAdded(geometry);
  54154. });
  54155. break;
  54156. case WorkerTaskType.UPDATE:
  54157. _this._runningUpdated--;
  54158. break;
  54159. case WorkerTaskType.COLLIDE:
  54160. var returnPayload = returnData.payload;
  54161. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54162. return;
  54163. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54164. if (callback) {
  54165. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54166. if (mesh) {
  54167. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54168. }
  54169. }
  54170. //cleanup
  54171. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54172. break;
  54173. }
  54174. };
  54175. this._collisionsCallbackArray = [];
  54176. this._init = false;
  54177. this._runningUpdated = 0;
  54178. this._addUpdateMeshesList = {};
  54179. this._addUpdateGeometriesList = {};
  54180. this._toRemoveGeometryArray = [];
  54181. this._toRemoveMeshesArray = [];
  54182. }
  54183. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54184. if (!this._init)
  54185. return;
  54186. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54187. return;
  54188. position.divideToRef(collider._radius, this._scaledPosition);
  54189. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54190. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54191. var payload = {
  54192. collider: {
  54193. position: this._scaledPosition.asArray(),
  54194. velocity: this._scaledVelocity.asArray(),
  54195. radius: collider._radius.asArray()
  54196. },
  54197. collisionId: collisionIndex,
  54198. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54199. maximumRetry: maximumRetry
  54200. };
  54201. var message = {
  54202. payload: payload,
  54203. taskType: WorkerTaskType.COLLIDE
  54204. };
  54205. this._worker.postMessage(message);
  54206. };
  54207. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54208. this._scene = scene;
  54209. this._scene.registerAfterRender(this._afterRender);
  54210. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54211. this._worker = new Worker(workerUrl);
  54212. this._worker.onmessage = this._onMessageFromWorker;
  54213. var message = {
  54214. payload: {},
  54215. taskType: WorkerTaskType.INIT
  54216. };
  54217. this._worker.postMessage(message);
  54218. };
  54219. CollisionCoordinatorWorker.prototype.destroy = function () {
  54220. this._scene.unregisterAfterRender(this._afterRender);
  54221. this._worker.terminate();
  54222. };
  54223. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54224. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54225. this.onMeshUpdated(mesh);
  54226. };
  54227. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54228. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54229. };
  54230. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54231. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54232. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54233. this.onGeometryUpdated(geometry);
  54234. };
  54235. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54236. this._toRemoveGeometryArray.push(geometry.id);
  54237. };
  54238. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54239. var submeshes = [];
  54240. if (mesh.subMeshes) {
  54241. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54242. var boundingInfo = sm.getBoundingInfo();
  54243. return {
  54244. position: idx,
  54245. verticesStart: sm.verticesStart,
  54246. verticesCount: sm.verticesCount,
  54247. indexStart: sm.indexStart,
  54248. indexCount: sm.indexCount,
  54249. hasMaterial: !!sm.getMaterial(),
  54250. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54251. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54252. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54253. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54254. };
  54255. });
  54256. }
  54257. var geometryId = null;
  54258. if (mesh instanceof BABYLON.Mesh) {
  54259. var geometry = mesh.geometry;
  54260. geometryId = geometry ? geometry.id : null;
  54261. }
  54262. else if (mesh instanceof BABYLON.InstancedMesh) {
  54263. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54264. geometryId = geometry ? geometry.id : null;
  54265. }
  54266. var boundingInfo = mesh.getBoundingInfo();
  54267. return {
  54268. uniqueId: mesh.uniqueId,
  54269. id: mesh.id,
  54270. name: mesh.name,
  54271. geometryId: geometryId,
  54272. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54273. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54274. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54275. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54276. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54277. subMeshes: submeshes,
  54278. checkCollisions: mesh.checkCollisions
  54279. };
  54280. };
  54281. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54282. return {
  54283. id: geometry.id,
  54284. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54285. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54286. indices: new Uint32Array(geometry.getIndices() || []),
  54287. };
  54288. };
  54289. return CollisionCoordinatorWorker;
  54290. }());
  54291. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54292. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54293. function CollisionCoordinatorLegacy() {
  54294. this._scaledPosition = BABYLON.Vector3.Zero();
  54295. this._scaledVelocity = BABYLON.Vector3.Zero();
  54296. this._finalPosition = BABYLON.Vector3.Zero();
  54297. }
  54298. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54299. position.divideToRef(collider._radius, this._scaledPosition);
  54300. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54301. collider.collidedMesh = null;
  54302. collider._retry = 0;
  54303. collider._initialVelocity = this._scaledVelocity;
  54304. collider._initialPosition = this._scaledPosition;
  54305. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54306. this._finalPosition.multiplyInPlace(collider._radius);
  54307. //run the callback
  54308. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54309. };
  54310. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54311. this._scene = scene;
  54312. };
  54313. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54314. //Legacy need no destruction method.
  54315. };
  54316. //No update in legacy mode
  54317. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54318. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54319. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54320. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54321. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54322. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54323. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54324. if (excludedMesh === void 0) { excludedMesh = null; }
  54325. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54326. if (collider._retry >= maximumRetry) {
  54327. finalPosition.copyFrom(position);
  54328. return;
  54329. }
  54330. // Check if this is a mesh else camera or -1
  54331. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54332. collider._initialize(position, velocity, closeDistance);
  54333. // Check all meshes
  54334. for (var index = 0; index < this._scene.meshes.length; index++) {
  54335. var mesh = this._scene.meshes[index];
  54336. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54337. mesh._checkCollision(collider);
  54338. }
  54339. }
  54340. if (!collider.collisionFound) {
  54341. position.addToRef(velocity, finalPosition);
  54342. return;
  54343. }
  54344. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54345. collider._getResponse(position, velocity);
  54346. }
  54347. if (velocity.length() <= closeDistance) {
  54348. finalPosition.copyFrom(position);
  54349. return;
  54350. }
  54351. collider._retry++;
  54352. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54353. };
  54354. return CollisionCoordinatorLegacy;
  54355. }());
  54356. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54357. })(BABYLON || (BABYLON = {}));
  54358. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54359. var BABYLON;
  54360. (function (BABYLON) {
  54361. /**
  54362. * A particle represents one of the element emitted by a particle system.
  54363. * This is mainly define by its coordinates, direction, velocity and age.
  54364. */
  54365. var Particle = /** @class */ (function () {
  54366. /**
  54367. * Creates a new instance Particle
  54368. * @param particleSystem the particle system the particle belongs to
  54369. */
  54370. function Particle(
  54371. /**
  54372. * particleSystem the particle system the particle belongs to.
  54373. */
  54374. particleSystem) {
  54375. this.particleSystem = particleSystem;
  54376. /**
  54377. * The world position of the particle in the scene.
  54378. */
  54379. this.position = BABYLON.Vector3.Zero();
  54380. /**
  54381. * The world direction of the particle in the scene.
  54382. */
  54383. this.direction = BABYLON.Vector3.Zero();
  54384. /**
  54385. * The color of the particle.
  54386. */
  54387. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54388. /**
  54389. * The color change of the particle per step.
  54390. */
  54391. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54392. /**
  54393. * Defines how long will the life of the particle be.
  54394. */
  54395. this.lifeTime = 1.0;
  54396. /**
  54397. * The current age of the particle.
  54398. */
  54399. this.age = 0;
  54400. /**
  54401. * The current size of the particle.
  54402. */
  54403. this.size = 0;
  54404. /**
  54405. * The current scale of the particle.
  54406. */
  54407. this.scale = new BABYLON.Vector2(1, 1);
  54408. /**
  54409. * The current angle of the particle.
  54410. */
  54411. this.angle = 0;
  54412. /**
  54413. * Defines how fast is the angle changing.
  54414. */
  54415. this.angularSpeed = 0;
  54416. /**
  54417. * Defines the cell index used by the particle to be rendered from a sprite.
  54418. */
  54419. this.cellIndex = 0;
  54420. /** @hidden */
  54421. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54422. /** @hidden */
  54423. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54424. /** @hidden */
  54425. this._currentSize1 = 0;
  54426. /** @hidden */
  54427. this._currentSize2 = 0;
  54428. /** @hidden */
  54429. this._currentAngularSpeed1 = 0;
  54430. /** @hidden */
  54431. this._currentAngularSpeed2 = 0;
  54432. /** @hidden */
  54433. this._currentVelocity1 = 0;
  54434. /** @hidden */
  54435. this._currentVelocity2 = 0;
  54436. if (!this.particleSystem.isAnimationSheetEnabled) {
  54437. return;
  54438. }
  54439. this.updateCellInfoFromSystem();
  54440. }
  54441. Particle.prototype.updateCellInfoFromSystem = function () {
  54442. this.cellIndex = this.particleSystem.startSpriteCellID;
  54443. };
  54444. /**
  54445. * Defines how the sprite cell index is updated for the particle
  54446. */
  54447. Particle.prototype.updateCellIndex = function () {
  54448. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54449. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54450. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54451. };
  54452. /**
  54453. * Copy the properties of particle to another one.
  54454. * @param other the particle to copy the information to.
  54455. */
  54456. Particle.prototype.copyTo = function (other) {
  54457. other.position.copyFrom(this.position);
  54458. if (this._initialDirection) {
  54459. if (other._initialDirection) {
  54460. other._initialDirection.copyFrom(this._initialDirection);
  54461. }
  54462. else {
  54463. other._initialDirection = this._initialDirection.clone();
  54464. }
  54465. }
  54466. else {
  54467. other._initialDirection = null;
  54468. }
  54469. other.direction.copyFrom(this.direction);
  54470. other.color.copyFrom(this.color);
  54471. other.colorStep.copyFrom(this.colorStep);
  54472. other.lifeTime = this.lifeTime;
  54473. other.age = this.age;
  54474. other.size = this.size;
  54475. other.scale.copyFrom(this.scale);
  54476. other.angle = this.angle;
  54477. other.angularSpeed = this.angularSpeed;
  54478. other.particleSystem = this.particleSystem;
  54479. other.cellIndex = this.cellIndex;
  54480. if (this._currentColorGradient) {
  54481. other._currentColorGradient = this._currentColorGradient;
  54482. other._currentColor1.copyFrom(this._currentColor1);
  54483. other._currentColor2.copyFrom(this._currentColor2);
  54484. }
  54485. if (this._currentSizeGradient) {
  54486. other._currentSizeGradient = this._currentSizeGradient;
  54487. other._currentSize1 = this._currentSize1;
  54488. other._currentSize2 = this._currentSize2;
  54489. }
  54490. if (this._currentAngularSpeedGradient) {
  54491. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54492. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54493. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54494. }
  54495. if (this._currentVelocityGradient) {
  54496. other._currentVelocityGradient = this._currentVelocityGradient;
  54497. other._currentVelocity1 = this._currentVelocity1;
  54498. other._currentVelocity2 = this._currentVelocity2;
  54499. }
  54500. if (this.particleSystem.isAnimationSheetEnabled) {
  54501. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54502. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54503. }
  54504. };
  54505. return Particle;
  54506. }());
  54507. BABYLON.Particle = Particle;
  54508. })(BABYLON || (BABYLON = {}));
  54509. //# sourceMappingURL=babylon.particle.js.map
  54510. var BABYLON;
  54511. (function (BABYLON) {
  54512. /**
  54513. * This represents a particle system in Babylon.
  54514. * 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.
  54515. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54516. * @example https://doc.babylonjs.com/babylon101/particles
  54517. */
  54518. var ParticleSystem = /** @class */ (function () {
  54519. /**
  54520. * Instantiates a particle system.
  54521. * 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.
  54522. * @param name The name of the particle system
  54523. * @param capacity The max number of particles alive at the same time
  54524. * @param scene The scene the particle system belongs to
  54525. * @param customEffect a custom effect used to change the way particles are rendered by default
  54526. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54527. * @param epsilon Offset used to render the particles
  54528. */
  54529. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54530. if (customEffect === void 0) { customEffect = null; }
  54531. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54532. if (epsilon === void 0) { epsilon = 0.01; }
  54533. var _this = this;
  54534. /**
  54535. * List of animations used by the particle system.
  54536. */
  54537. this.animations = [];
  54538. /**
  54539. * The rendering group used by the Particle system to chose when to render.
  54540. */
  54541. this.renderingGroupId = 0;
  54542. /**
  54543. * The emitter represents the Mesh or position we are attaching the particle system to.
  54544. */
  54545. this.emitter = null;
  54546. /**
  54547. * The maximum number of particles to emit per frame
  54548. */
  54549. this.emitRate = 10;
  54550. /**
  54551. * If you want to launch only a few particles at once, that can be done, as well.
  54552. */
  54553. this.manualEmitCount = -1;
  54554. /**
  54555. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54556. */
  54557. this.updateSpeed = 0.01;
  54558. /**
  54559. * The amount of time the particle system is running (depends of the overall update speed).
  54560. */
  54561. this.targetStopDuration = 0;
  54562. /**
  54563. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54564. */
  54565. this.disposeOnStop = false;
  54566. /**
  54567. * Minimum power of emitting particles.
  54568. */
  54569. this.minEmitPower = 1;
  54570. /**
  54571. * Maximum power of emitting particles.
  54572. */
  54573. this.maxEmitPower = 1;
  54574. /**
  54575. * Minimum life time of emitting particles.
  54576. */
  54577. this.minLifeTime = 1;
  54578. /**
  54579. * Maximum life time of emitting particles.
  54580. */
  54581. this.maxLifeTime = 1;
  54582. /**
  54583. * Minimum Size of emitting particles.
  54584. */
  54585. this.minSize = 1;
  54586. /**
  54587. * Maximum Size of emitting particles.
  54588. */
  54589. this.maxSize = 1;
  54590. /**
  54591. * Minimum scale of emitting particles on X axis.
  54592. */
  54593. this.minScaleX = 1;
  54594. /**
  54595. * Maximum scale of emitting particles on X axis.
  54596. */
  54597. this.maxScaleX = 1;
  54598. /**
  54599. * Minimum scale of emitting particles on Y axis.
  54600. */
  54601. this.minScaleY = 1;
  54602. /**
  54603. * Maximum scale of emitting particles on Y axis.
  54604. */
  54605. this.maxScaleY = 1;
  54606. /**
  54607. * Gets or sets the minimal initial rotation in radians.
  54608. */
  54609. this.minInitialRotation = 0;
  54610. /**
  54611. * Gets or sets the maximal initial rotation in radians.
  54612. */
  54613. this.maxInitialRotation = 0;
  54614. /**
  54615. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54616. */
  54617. this.minAngularSpeed = 0;
  54618. /**
  54619. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54620. */
  54621. this.maxAngularSpeed = 0;
  54622. /**
  54623. * The layer mask we are rendering the particles through.
  54624. */
  54625. this.layerMask = 0x0FFFFFFF;
  54626. /**
  54627. * This can help using your own shader to render the particle system.
  54628. * The according effect will be created
  54629. */
  54630. this.customShader = null;
  54631. /**
  54632. * By default particle system starts as soon as they are created. This prevents the
  54633. * automatic start to happen and let you decide when to start emitting particles.
  54634. */
  54635. this.preventAutoStart = false;
  54636. /**
  54637. * Callback triggered when the particle animation is ending.
  54638. */
  54639. this.onAnimationEnd = null;
  54640. /**
  54641. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54642. */
  54643. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54644. /**
  54645. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54646. * to override the particles.
  54647. */
  54648. this.forceDepthWrite = false;
  54649. /**
  54650. * You can use gravity if you want to give an orientation to your particles.
  54651. */
  54652. this.gravity = BABYLON.Vector3.Zero();
  54653. this._colorGradients = null;
  54654. this._sizeGradients = null;
  54655. this._lifeTimeGradients = null;
  54656. this._angularSpeedGradients = null;
  54657. this._velocityGradients = null;
  54658. /**
  54659. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54660. */
  54661. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54662. /**
  54663. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54664. */
  54665. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54666. /**
  54667. * Color the particle will have at the end of its lifetime
  54668. */
  54669. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54670. /**
  54671. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  54672. */
  54673. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54674. /**
  54675. * 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)
  54676. */
  54677. this.spriteCellChangeSpeed = 1;
  54678. /**
  54679. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  54680. */
  54681. this.startSpriteCellID = 0;
  54682. /**
  54683. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  54684. */
  54685. this.endSpriteCellID = 0;
  54686. /**
  54687. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  54688. */
  54689. this.spriteCellWidth = 0;
  54690. /**
  54691. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  54692. */
  54693. this.spriteCellHeight = 0;
  54694. /** 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 */
  54695. this.preWarmCycles = 0;
  54696. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  54697. this.preWarmStepOffset = 1;
  54698. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  54699. this.translationPivot = new BABYLON.Vector2(0, 0);
  54700. /**
  54701. * An event triggered when the system is disposed
  54702. */
  54703. this.onDisposeObservable = new BABYLON.Observable();
  54704. /**
  54705. * Gets or sets the billboard mode to use when isBillboardBased = true.
  54706. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  54707. */
  54708. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54709. this._particles = new Array();
  54710. this._stockParticles = new Array();
  54711. this._newPartsExcess = 0;
  54712. this._vertexBuffers = {};
  54713. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54714. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54715. this._scaledDirection = BABYLON.Vector3.Zero();
  54716. this._scaledGravity = BABYLON.Vector3.Zero();
  54717. this._currentRenderId = -1;
  54718. this._useInstancing = false;
  54719. this._started = false;
  54720. this._stopped = false;
  54721. this._actualFrame = 0;
  54722. this._isBillboardBased = true;
  54723. // start of sub system methods
  54724. /**
  54725. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54726. * Its lifetime will start back at 0.
  54727. */
  54728. this.recycleParticle = function (particle) {
  54729. var lastParticle = _this._particles.pop();
  54730. if (lastParticle !== particle) {
  54731. lastParticle.copyTo(particle);
  54732. }
  54733. _this._stockParticles.push(lastParticle);
  54734. };
  54735. this._createParticle = function () {
  54736. var particle;
  54737. if (_this._stockParticles.length !== 0) {
  54738. particle = _this._stockParticles.pop();
  54739. particle.age = 0;
  54740. particle._currentColorGradient = null;
  54741. particle.cellIndex = _this.startSpriteCellID;
  54742. }
  54743. else {
  54744. particle = new BABYLON.Particle(_this);
  54745. }
  54746. return particle;
  54747. };
  54748. this._emitFromParticle = function (particle) {
  54749. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54750. return;
  54751. }
  54752. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54753. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54754. subSystem._rootParticleSystem = _this;
  54755. _this.activeSubSystems.push(subSystem);
  54756. subSystem.start();
  54757. };
  54758. this.id = name;
  54759. this.name = name;
  54760. this._capacity = capacity;
  54761. this._epsilon = epsilon;
  54762. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54763. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54764. this._customEffect = customEffect;
  54765. scene.particleSystems.push(this);
  54766. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  54767. this._createIndexBuffer();
  54768. this._createVertexBuffers();
  54769. // Default emitter type
  54770. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54771. this.updateFunction = function (particles) {
  54772. var _loop_1 = function () {
  54773. particle = particles[index];
  54774. particle.age += _this._scaledUpdateSpeed;
  54775. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  54776. _this._emitFromParticle(particle);
  54777. _this.recycleParticle(particle);
  54778. index--;
  54779. return "continue";
  54780. }
  54781. else {
  54782. var ratio = particle.age / particle.lifeTime;
  54783. // Color
  54784. if (_this._colorGradients && _this._colorGradients.length > 0) {
  54785. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  54786. if (currentGradient !== particle._currentColorGradient) {
  54787. particle._currentColor1.copyFrom(particle._currentColor2);
  54788. nextGradient.getColorToRef(particle._currentColor2);
  54789. particle._currentColorGradient = currentGradient;
  54790. }
  54791. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  54792. });
  54793. }
  54794. else {
  54795. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54796. particle.color.addInPlace(_this._scaledColorStep);
  54797. if (particle.color.a < 0) {
  54798. particle.color.a = 0;
  54799. }
  54800. }
  54801. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  54802. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  54803. if (currentGradient !== particle._currentAngularSpeedGradient) {
  54804. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  54805. particle._currentAngularSpeed2 = nextGradient.getFactor();
  54806. particle._currentAngularSpeedGradient = currentGradient;
  54807. }
  54808. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  54809. });
  54810. }
  54811. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54812. var directionScale_1 = _this._scaledUpdateSpeed;
  54813. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  54814. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  54815. if (currentGradient !== particle._currentVelocityGradient) {
  54816. particle._currentVelocity1 = particle._currentVelocity2;
  54817. particle._currentVelocity2 = nextGradient.getFactor();
  54818. particle._currentVelocityGradient = currentGradient;
  54819. }
  54820. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  54821. });
  54822. }
  54823. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  54824. particle.position.addInPlace(_this._scaledDirection);
  54825. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54826. particle.direction.addInPlace(_this._scaledGravity);
  54827. // Size
  54828. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  54829. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  54830. if (currentGradient !== particle._currentSizeGradient) {
  54831. particle._currentSize1 = particle._currentSize2;
  54832. particle._currentSize2 = nextGradient.getFactor();
  54833. particle._currentSizeGradient = currentGradient;
  54834. }
  54835. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  54836. });
  54837. }
  54838. if (_this._isAnimationSheetEnabled) {
  54839. particle.updateCellIndex();
  54840. }
  54841. }
  54842. };
  54843. var particle;
  54844. for (var index = 0; index < particles.length; index++) {
  54845. _loop_1();
  54846. }
  54847. };
  54848. }
  54849. /**
  54850. * Gets the current list of color gradients.
  54851. * You must use addColorGradient and removeColorGradient to udpate this list
  54852. * @returns the list of color gradients
  54853. */
  54854. ParticleSystem.prototype.getColorGradients = function () {
  54855. return this._colorGradients;
  54856. };
  54857. /**
  54858. * Gets the current list of size gradients.
  54859. * You must use addSizeGradient and removeSizeGradient to udpate this list
  54860. * @returns the list of size gradients
  54861. */
  54862. ParticleSystem.prototype.getSizeGradients = function () {
  54863. return this._sizeGradients;
  54864. };
  54865. /**
  54866. * Gets the current list of life time gradients.
  54867. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  54868. * @returns the list of life time gradients
  54869. */
  54870. ParticleSystem.prototype.getLifeTimeGradients = function () {
  54871. return this._lifeTimeGradients;
  54872. };
  54873. /**
  54874. * Gets the current list of angular speed gradients.
  54875. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  54876. * @returns the list of angular speed gradients
  54877. */
  54878. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  54879. return this._angularSpeedGradients;
  54880. };
  54881. /**
  54882. * Gets the current list of velocity gradients.
  54883. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  54884. * @returns the list of velocity gradients
  54885. */
  54886. ParticleSystem.prototype.getVelocityGradients = function () {
  54887. return this._velocityGradients;
  54888. };
  54889. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54890. /**
  54891. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54892. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54893. */
  54894. get: function () {
  54895. if (this.particleEmitterType.direction1) {
  54896. return this.particleEmitterType.direction1;
  54897. }
  54898. return BABYLON.Vector3.Zero();
  54899. },
  54900. set: function (value) {
  54901. if (this.particleEmitterType.direction1) {
  54902. this.particleEmitterType.direction1 = value;
  54903. }
  54904. },
  54905. enumerable: true,
  54906. configurable: true
  54907. });
  54908. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54909. /**
  54910. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54911. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54912. */
  54913. get: function () {
  54914. if (this.particleEmitterType.direction2) {
  54915. return this.particleEmitterType.direction2;
  54916. }
  54917. return BABYLON.Vector3.Zero();
  54918. },
  54919. set: function (value) {
  54920. if (this.particleEmitterType.direction2) {
  54921. this.particleEmitterType.direction2 = value;
  54922. }
  54923. },
  54924. enumerable: true,
  54925. configurable: true
  54926. });
  54927. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54928. /**
  54929. * 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.
  54930. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54931. */
  54932. get: function () {
  54933. if (this.particleEmitterType.minEmitBox) {
  54934. return this.particleEmitterType.minEmitBox;
  54935. }
  54936. return BABYLON.Vector3.Zero();
  54937. },
  54938. set: function (value) {
  54939. if (this.particleEmitterType.minEmitBox) {
  54940. this.particleEmitterType.minEmitBox = value;
  54941. }
  54942. },
  54943. enumerable: true,
  54944. configurable: true
  54945. });
  54946. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54947. /**
  54948. * 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.
  54949. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54950. */
  54951. get: function () {
  54952. if (this.particleEmitterType.maxEmitBox) {
  54953. return this.particleEmitterType.maxEmitBox;
  54954. }
  54955. return BABYLON.Vector3.Zero();
  54956. },
  54957. set: function (value) {
  54958. if (this.particleEmitterType.maxEmitBox) {
  54959. this.particleEmitterType.maxEmitBox = value;
  54960. }
  54961. },
  54962. enumerable: true,
  54963. configurable: true
  54964. });
  54965. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54966. /**
  54967. * Sets a callback that will be triggered when the system is disposed
  54968. */
  54969. set: function (callback) {
  54970. if (this._onDisposeObserver) {
  54971. this.onDisposeObservable.remove(this._onDisposeObserver);
  54972. }
  54973. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54974. },
  54975. enumerable: true,
  54976. configurable: true
  54977. });
  54978. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54979. /**
  54980. * Gets whether an animation sprite sheet is enabled or not on the particle system
  54981. */
  54982. get: function () {
  54983. return this._isAnimationSheetEnabled;
  54984. },
  54985. enumerable: true,
  54986. configurable: true
  54987. });
  54988. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  54989. /**
  54990. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  54991. */
  54992. get: function () {
  54993. return this._isBillboardBased;
  54994. },
  54995. set: function (value) {
  54996. if (this._isBillboardBased === value) {
  54997. return;
  54998. }
  54999. this._isBillboardBased = value;
  55000. this._resetEffect();
  55001. },
  55002. enumerable: true,
  55003. configurable: true
  55004. });
  55005. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55006. //end of Sub-emitter
  55007. /**
  55008. * Gets the current list of active particles
  55009. */
  55010. get: function () {
  55011. return this._particles;
  55012. },
  55013. enumerable: true,
  55014. configurable: true
  55015. });
  55016. /**
  55017. * Returns the string "ParticleSystem"
  55018. * @returns a string containing the class name
  55019. */
  55020. ParticleSystem.prototype.getClassName = function () {
  55021. return "ParticleSystem";
  55022. };
  55023. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55024. var newGradient = new BABYLON.FactorGradient();
  55025. newGradient.gradient = gradient;
  55026. newGradient.factor1 = factor;
  55027. newGradient.factor2 = factor2;
  55028. factorGradients.push(newGradient);
  55029. factorGradients.sort(function (a, b) {
  55030. if (a.gradient < b.gradient) {
  55031. return -1;
  55032. }
  55033. else if (a.gradient > b.gradient) {
  55034. return 1;
  55035. }
  55036. return 0;
  55037. });
  55038. };
  55039. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55040. if (!factorGradients) {
  55041. return;
  55042. }
  55043. var index = 0;
  55044. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55045. var factorGradient = factorGradients_1[_i];
  55046. if (factorGradient.gradient === gradient) {
  55047. factorGradients.splice(index, 1);
  55048. break;
  55049. }
  55050. index++;
  55051. }
  55052. };
  55053. /**
  55054. * Adds a new life time gradient
  55055. * @param gradient defines the gradient to use (between 0 and 1)
  55056. * @param factor defines the life time factor to affect to the specified gradient
  55057. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55058. * @returns the current particle system
  55059. */
  55060. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55061. if (!this._lifeTimeGradients) {
  55062. this._lifeTimeGradients = [];
  55063. }
  55064. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55065. return this;
  55066. };
  55067. /**
  55068. * Remove a specific life time gradient
  55069. * @param gradient defines the gradient to remove
  55070. * @returns the current particle system
  55071. */
  55072. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55073. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55074. return this;
  55075. };
  55076. /**
  55077. * Adds a new size gradient
  55078. * @param gradient defines the gradient to use (between 0 and 1)
  55079. * @param factor defines the size factor to affect to the specified gradient
  55080. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55081. * @returns the current particle system
  55082. */
  55083. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55084. if (!this._sizeGradients) {
  55085. this._sizeGradients = [];
  55086. }
  55087. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55088. return this;
  55089. };
  55090. /**
  55091. * Remove a specific size gradient
  55092. * @param gradient defines the gradient to remove
  55093. * @returns the current particle system
  55094. */
  55095. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55096. this._removeFactorGradient(this._sizeGradients, gradient);
  55097. return this;
  55098. };
  55099. /**
  55100. * Adds a new angular speed gradient
  55101. * @param gradient defines the gradient to use (between 0 and 1)
  55102. * @param factor defines the size factor to affect to the specified gradient
  55103. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55104. * @returns the current particle system
  55105. */
  55106. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55107. if (!this._angularSpeedGradients) {
  55108. this._angularSpeedGradients = [];
  55109. }
  55110. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55111. return this;
  55112. };
  55113. /**
  55114. * Remove a specific angular speed gradient
  55115. * @param gradient defines the gradient to remove
  55116. * @returns the current particle system
  55117. */
  55118. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55119. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55120. return this;
  55121. };
  55122. /**
  55123. * Adds a new velocity gradient
  55124. * @param gradient defines the gradient to use (between 0 and 1)
  55125. * @param factor defines the size factor to affect to the specified gradient
  55126. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55127. * @returns the current particle system
  55128. */
  55129. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55130. if (!this._velocityGradients) {
  55131. this._velocityGradients = [];
  55132. }
  55133. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55134. return this;
  55135. };
  55136. /**
  55137. * Remove a specific velocity gradient
  55138. * @param gradient defines the gradient to remove
  55139. * @returns the current particle system
  55140. */
  55141. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55142. this._removeFactorGradient(this._velocityGradients, gradient);
  55143. return this;
  55144. };
  55145. /**
  55146. * Adds a new color gradient
  55147. * @param gradient defines the gradient to use (between 0 and 1)
  55148. * @param color defines the color to affect to the specified gradient
  55149. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55150. */
  55151. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55152. if (!this._colorGradients) {
  55153. this._colorGradients = [];
  55154. }
  55155. var colorGradient = new BABYLON.ColorGradient();
  55156. colorGradient.gradient = gradient;
  55157. colorGradient.color1 = color;
  55158. colorGradient.color2 = color2;
  55159. this._colorGradients.push(colorGradient);
  55160. this._colorGradients.sort(function (a, b) {
  55161. if (a.gradient < b.gradient) {
  55162. return -1;
  55163. }
  55164. else if (a.gradient > b.gradient) {
  55165. return 1;
  55166. }
  55167. return 0;
  55168. });
  55169. return this;
  55170. };
  55171. /**
  55172. * Remove a specific color gradient
  55173. * @param gradient defines the gradient to remove
  55174. */
  55175. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55176. if (!this._colorGradients) {
  55177. return this;
  55178. }
  55179. var index = 0;
  55180. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55181. var colorGradient = _a[_i];
  55182. if (colorGradient.gradient === gradient) {
  55183. this._colorGradients.splice(index, 1);
  55184. break;
  55185. }
  55186. index++;
  55187. }
  55188. return this;
  55189. };
  55190. ParticleSystem.prototype._resetEffect = function () {
  55191. if (this._vertexBuffer) {
  55192. this._vertexBuffer.dispose();
  55193. this._vertexBuffer = null;
  55194. }
  55195. if (this._spriteBuffer) {
  55196. this._spriteBuffer.dispose();
  55197. this._spriteBuffer = null;
  55198. }
  55199. this._createVertexBuffers();
  55200. };
  55201. ParticleSystem.prototype._createVertexBuffers = function () {
  55202. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55203. if (this._isAnimationSheetEnabled) {
  55204. this._vertexBufferSize += 1;
  55205. }
  55206. if (!this._isBillboardBased) {
  55207. this._vertexBufferSize += 3;
  55208. }
  55209. var engine = this._scene.getEngine();
  55210. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55211. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55212. var dataOffset = 0;
  55213. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55214. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55215. dataOffset += 3;
  55216. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55217. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55218. dataOffset += 4;
  55219. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55220. this._vertexBuffers["angle"] = options;
  55221. dataOffset += 1;
  55222. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55223. this._vertexBuffers["size"] = size;
  55224. dataOffset += 2;
  55225. if (this._isAnimationSheetEnabled) {
  55226. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55227. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55228. dataOffset += 1;
  55229. }
  55230. if (!this._isBillboardBased) {
  55231. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55232. this._vertexBuffers["direction"] = directionBuffer;
  55233. dataOffset += 3;
  55234. }
  55235. var offsets;
  55236. if (this._useInstancing) {
  55237. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55238. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55239. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55240. }
  55241. else {
  55242. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55243. dataOffset += 2;
  55244. }
  55245. this._vertexBuffers["offset"] = offsets;
  55246. };
  55247. ParticleSystem.prototype._createIndexBuffer = function () {
  55248. if (this._useInstancing) {
  55249. return;
  55250. }
  55251. var indices = [];
  55252. var index = 0;
  55253. for (var count = 0; count < this._capacity; count++) {
  55254. indices.push(index);
  55255. indices.push(index + 1);
  55256. indices.push(index + 2);
  55257. indices.push(index);
  55258. indices.push(index + 2);
  55259. indices.push(index + 3);
  55260. index += 4;
  55261. }
  55262. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55263. };
  55264. /**
  55265. * Gets the maximum number of particles active at the same time.
  55266. * @returns The max number of active particles.
  55267. */
  55268. ParticleSystem.prototype.getCapacity = function () {
  55269. return this._capacity;
  55270. };
  55271. /**
  55272. * Gets Wether there are still active particles in the system.
  55273. * @returns True if it is alive, otherwise false.
  55274. */
  55275. ParticleSystem.prototype.isAlive = function () {
  55276. return this._alive;
  55277. };
  55278. /**
  55279. * Gets Wether the system has been started.
  55280. * @returns True if it has been started, otherwise false.
  55281. */
  55282. ParticleSystem.prototype.isStarted = function () {
  55283. return this._started;
  55284. };
  55285. /**
  55286. * Starts the particle system and begins to emit
  55287. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55288. */
  55289. ParticleSystem.prototype.start = function (delay) {
  55290. var _this = this;
  55291. if (delay === void 0) { delay = 0; }
  55292. if (delay) {
  55293. setTimeout(function () {
  55294. _this.start(0);
  55295. }, delay);
  55296. return;
  55297. }
  55298. this._started = true;
  55299. this._stopped = false;
  55300. this._actualFrame = 0;
  55301. if (this.subEmitters && this.subEmitters.length != 0) {
  55302. this.activeSubSystems = new Array();
  55303. }
  55304. if (this.preWarmCycles) {
  55305. for (var index = 0; index < this.preWarmCycles; index++) {
  55306. this.animate(true);
  55307. }
  55308. }
  55309. };
  55310. /**
  55311. * Stops the particle system.
  55312. * @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.
  55313. */
  55314. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55315. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55316. this._stopped = true;
  55317. if (stopSubEmitters) {
  55318. this._stopSubEmitters();
  55319. }
  55320. };
  55321. // animation sheet
  55322. /**
  55323. * Remove all active particles
  55324. */
  55325. ParticleSystem.prototype.reset = function () {
  55326. this._stockParticles = [];
  55327. this._particles = [];
  55328. };
  55329. /**
  55330. * @hidden (for internal use only)
  55331. */
  55332. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55333. var offset = index * this._vertexBufferSize;
  55334. this._vertexData[offset++] = particle.position.x;
  55335. this._vertexData[offset++] = particle.position.y;
  55336. this._vertexData[offset++] = particle.position.z;
  55337. this._vertexData[offset++] = particle.color.r;
  55338. this._vertexData[offset++] = particle.color.g;
  55339. this._vertexData[offset++] = particle.color.b;
  55340. this._vertexData[offset++] = particle.color.a;
  55341. this._vertexData[offset++] = particle.angle;
  55342. this._vertexData[offset++] = particle.scale.x * particle.size;
  55343. this._vertexData[offset++] = particle.scale.y * particle.size;
  55344. if (this._isAnimationSheetEnabled) {
  55345. this._vertexData[offset++] = particle.cellIndex;
  55346. }
  55347. if (!this._isBillboardBased) {
  55348. if (particle._initialDirection) {
  55349. this._vertexData[offset++] = particle._initialDirection.x;
  55350. this._vertexData[offset++] = particle._initialDirection.y;
  55351. this._vertexData[offset++] = particle._initialDirection.z;
  55352. }
  55353. else {
  55354. this._vertexData[offset++] = particle.direction.x;
  55355. this._vertexData[offset++] = particle.direction.y;
  55356. this._vertexData[offset++] = particle.direction.z;
  55357. }
  55358. }
  55359. if (!this._useInstancing) {
  55360. if (this._isAnimationSheetEnabled) {
  55361. if (offsetX === 0)
  55362. offsetX = this._epsilon;
  55363. else if (offsetX === 1)
  55364. offsetX = 1 - this._epsilon;
  55365. if (offsetY === 0)
  55366. offsetY = this._epsilon;
  55367. else if (offsetY === 1)
  55368. offsetY = 1 - this._epsilon;
  55369. }
  55370. this._vertexData[offset++] = offsetX;
  55371. this._vertexData[offset++] = offsetY;
  55372. }
  55373. };
  55374. ParticleSystem.prototype._stopSubEmitters = function () {
  55375. if (!this.activeSubSystems) {
  55376. return;
  55377. }
  55378. this.activeSubSystems.forEach(function (subSystem) {
  55379. subSystem.stop(true);
  55380. });
  55381. this.activeSubSystems = new Array();
  55382. };
  55383. ParticleSystem.prototype._removeFromRoot = function () {
  55384. if (!this._rootParticleSystem) {
  55385. return;
  55386. }
  55387. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55388. if (index !== -1) {
  55389. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55390. }
  55391. };
  55392. // End of sub system methods
  55393. ParticleSystem.prototype._update = function (newParticles) {
  55394. // Update current
  55395. this._alive = this._particles.length > 0;
  55396. this.updateFunction(this._particles);
  55397. // Add new ones
  55398. var worldMatrix;
  55399. if (this.emitter.position) {
  55400. var emitterMesh = this.emitter;
  55401. worldMatrix = emitterMesh.getWorldMatrix();
  55402. }
  55403. else {
  55404. var emitterPosition = this.emitter;
  55405. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55406. }
  55407. var particle;
  55408. var _loop_2 = function () {
  55409. if (this_1._particles.length === this_1._capacity) {
  55410. return "break";
  55411. }
  55412. particle = this_1._createParticle();
  55413. this_1._particles.push(particle);
  55414. // Emitter
  55415. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55416. if (this_1.startPositionFunction) {
  55417. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55418. }
  55419. else {
  55420. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55421. }
  55422. if (this_1.startDirectionFunction) {
  55423. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55424. }
  55425. else {
  55426. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55427. }
  55428. if (emitPower === 0) {
  55429. if (!particle._initialDirection) {
  55430. particle._initialDirection = particle.direction.clone();
  55431. }
  55432. else {
  55433. particle._initialDirection.copyFrom(particle.direction);
  55434. }
  55435. }
  55436. else {
  55437. particle._initialDirection = null;
  55438. }
  55439. particle.direction.scaleInPlace(emitPower);
  55440. // Life time
  55441. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55442. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55443. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55444. var factorGradient1 = currentGradient;
  55445. var factorGradient2 = nextGradient;
  55446. var lifeTime1 = factorGradient1.getFactor();
  55447. var lifeTime2 = factorGradient2.getFactor();
  55448. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55449. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55450. });
  55451. }
  55452. else {
  55453. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55454. }
  55455. // Size
  55456. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55457. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55458. }
  55459. else {
  55460. particle._currentSizeGradient = this_1._sizeGradients[0];
  55461. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55462. particle.size = particle._currentSize1;
  55463. if (this_1._sizeGradients.length > 1) {
  55464. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55465. }
  55466. else {
  55467. particle._currentSize2 = particle._currentSize1;
  55468. }
  55469. }
  55470. // Size and scale
  55471. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55472. // Angle
  55473. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55474. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55475. }
  55476. else {
  55477. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55478. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55479. particle._currentAngularSpeed1 = particle.angularSpeed;
  55480. if (this_1._angularSpeedGradients.length > 1) {
  55481. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55482. }
  55483. else {
  55484. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55485. }
  55486. }
  55487. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55488. // Velocity
  55489. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55490. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55491. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55492. if (this_1._velocityGradients.length > 1) {
  55493. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55494. }
  55495. else {
  55496. particle._currentVelocity2 = particle._currentVelocity1;
  55497. }
  55498. }
  55499. // Color
  55500. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55501. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55502. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55503. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55504. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55505. }
  55506. else {
  55507. particle._currentColorGradient = this_1._colorGradients[0];
  55508. particle._currentColorGradient.getColorToRef(particle.color);
  55509. particle._currentColor1.copyFrom(particle.color);
  55510. if (this_1._colorGradients.length > 1) {
  55511. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55512. }
  55513. else {
  55514. particle._currentColor2.copyFrom(particle.color);
  55515. }
  55516. }
  55517. // Sheet
  55518. if (this_1._isAnimationSheetEnabled) {
  55519. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55520. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55521. }
  55522. };
  55523. var this_1 = this, step;
  55524. for (var index = 0; index < newParticles; index++) {
  55525. var state_1 = _loop_2();
  55526. if (state_1 === "break")
  55527. break;
  55528. }
  55529. };
  55530. /** @hidden */
  55531. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55532. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55533. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55534. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55535. if (isAnimationSheetEnabled) {
  55536. attributeNamesOrOptions.push("cellIndex");
  55537. }
  55538. if (!isBillboardBased) {
  55539. attributeNamesOrOptions.push("direction");
  55540. }
  55541. return attributeNamesOrOptions;
  55542. };
  55543. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55544. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55545. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55546. if (isAnimationSheetEnabled) {
  55547. effectCreationOption.push("particlesInfos");
  55548. }
  55549. return effectCreationOption;
  55550. };
  55551. ParticleSystem.prototype._getEffect = function () {
  55552. if (this._customEffect) {
  55553. return this._customEffect;
  55554. }
  55555. ;
  55556. var defines = [];
  55557. if (this._scene.clipPlane) {
  55558. defines.push("#define CLIPPLANE");
  55559. }
  55560. if (this._isAnimationSheetEnabled) {
  55561. defines.push("#define ANIMATESHEET");
  55562. }
  55563. if (this._isBillboardBased) {
  55564. defines.push("#define BILLBOARD");
  55565. switch (this.billboardMode) {
  55566. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55567. defines.push("#define BILLBOARDY");
  55568. break;
  55569. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55570. default:
  55571. break;
  55572. }
  55573. }
  55574. // Effect
  55575. var join = defines.join("\n");
  55576. if (this._cachedDefines !== join) {
  55577. this._cachedDefines = join;
  55578. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55579. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55580. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55581. }
  55582. return this._effect;
  55583. };
  55584. /**
  55585. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55586. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55587. */
  55588. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55589. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55590. if (!this._started)
  55591. return;
  55592. if (!preWarmOnly) {
  55593. var effect = this._getEffect();
  55594. // Check
  55595. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55596. return;
  55597. if (this._currentRenderId === this._scene.getRenderId()) {
  55598. return;
  55599. }
  55600. this._currentRenderId = this._scene.getRenderId();
  55601. }
  55602. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55603. // determine the number of particles we need to create
  55604. var newParticles;
  55605. if (this.manualEmitCount > -1) {
  55606. newParticles = this.manualEmitCount;
  55607. this._newPartsExcess = 0;
  55608. this.manualEmitCount = 0;
  55609. }
  55610. else {
  55611. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55612. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55613. }
  55614. if (this._newPartsExcess > 1.0) {
  55615. newParticles += this._newPartsExcess >> 0;
  55616. this._newPartsExcess -= this._newPartsExcess >> 0;
  55617. }
  55618. this._alive = false;
  55619. if (!this._stopped) {
  55620. this._actualFrame += this._scaledUpdateSpeed;
  55621. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55622. this.stop();
  55623. }
  55624. else {
  55625. newParticles = 0;
  55626. }
  55627. this._update(newParticles);
  55628. // Stopped?
  55629. if (this._stopped) {
  55630. if (!this._alive) {
  55631. this._started = false;
  55632. if (this.onAnimationEnd) {
  55633. this.onAnimationEnd();
  55634. }
  55635. if (this.disposeOnStop) {
  55636. this._scene._toBeDisposed.push(this);
  55637. }
  55638. }
  55639. }
  55640. if (!preWarmOnly) {
  55641. // Update VBO
  55642. var offset = 0;
  55643. for (var index = 0; index < this._particles.length; index++) {
  55644. var particle = this._particles[index];
  55645. this._appendParticleVertices(offset, particle);
  55646. offset += this._useInstancing ? 1 : 4;
  55647. }
  55648. if (this._vertexBuffer) {
  55649. this._vertexBuffer.update(this._vertexData);
  55650. }
  55651. }
  55652. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55653. this.stop();
  55654. }
  55655. };
  55656. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55657. this._appendParticleVertex(offset++, particle, 0, 0);
  55658. if (!this._useInstancing) {
  55659. this._appendParticleVertex(offset++, particle, 1, 0);
  55660. this._appendParticleVertex(offset++, particle, 1, 1);
  55661. this._appendParticleVertex(offset++, particle, 0, 1);
  55662. }
  55663. };
  55664. /**
  55665. * Rebuilds the particle system.
  55666. */
  55667. ParticleSystem.prototype.rebuild = function () {
  55668. this._createIndexBuffer();
  55669. if (this._vertexBuffer) {
  55670. this._vertexBuffer._rebuild();
  55671. }
  55672. };
  55673. /**
  55674. * Is this system ready to be used/rendered
  55675. * @return true if the system is ready
  55676. */
  55677. ParticleSystem.prototype.isReady = function () {
  55678. var effect = this._getEffect();
  55679. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55680. return false;
  55681. }
  55682. return true;
  55683. };
  55684. /**
  55685. * Renders the particle system in its current state.
  55686. * @returns the current number of particles
  55687. */
  55688. ParticleSystem.prototype.render = function () {
  55689. var effect = this._getEffect();
  55690. // Check
  55691. if (!this.isReady() || !this._particles.length) {
  55692. return 0;
  55693. }
  55694. var engine = this._scene.getEngine();
  55695. // Render
  55696. engine.enableEffect(effect);
  55697. engine.setState(false);
  55698. var viewMatrix = this._scene.getViewMatrix();
  55699. effect.setTexture("diffuseSampler", this.particleTexture);
  55700. effect.setMatrix("view", viewMatrix);
  55701. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55702. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55703. var baseSize = this.particleTexture.getBaseSize();
  55704. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55705. }
  55706. effect.setVector2("translationPivot", this.translationPivot);
  55707. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55708. if (this._isBillboardBased) {
  55709. var camera = this._scene.activeCamera;
  55710. effect.setVector3("eyePosition", camera.globalPosition);
  55711. }
  55712. if (this._scene.clipPlane) {
  55713. var clipPlane = this._scene.clipPlane;
  55714. var invView = viewMatrix.clone();
  55715. invView.invert();
  55716. effect.setMatrix("invView", invView);
  55717. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55718. }
  55719. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55720. // Draw order
  55721. switch (this.blendMode) {
  55722. case ParticleSystem.BLENDMODE_ADD:
  55723. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55724. break;
  55725. case ParticleSystem.BLENDMODE_ONEONE:
  55726. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55727. break;
  55728. case ParticleSystem.BLENDMODE_STANDARD:
  55729. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55730. break;
  55731. }
  55732. if (this.forceDepthWrite) {
  55733. engine.setDepthWrite(true);
  55734. }
  55735. if (this._useInstancing) {
  55736. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55737. engine.unbindInstanceAttributes();
  55738. }
  55739. else {
  55740. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55741. }
  55742. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55743. return this._particles.length;
  55744. };
  55745. /**
  55746. * Disposes the particle system and free the associated resources
  55747. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55748. */
  55749. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55750. if (disposeTexture === void 0) { disposeTexture = true; }
  55751. if (this._vertexBuffer) {
  55752. this._vertexBuffer.dispose();
  55753. this._vertexBuffer = null;
  55754. }
  55755. if (this._spriteBuffer) {
  55756. this._spriteBuffer.dispose();
  55757. this._spriteBuffer = null;
  55758. }
  55759. if (this._indexBuffer) {
  55760. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55761. this._indexBuffer = null;
  55762. }
  55763. if (disposeTexture && this.particleTexture) {
  55764. this.particleTexture.dispose();
  55765. this.particleTexture = null;
  55766. }
  55767. this._removeFromRoot();
  55768. // Remove from scene
  55769. var index = this._scene.particleSystems.indexOf(this);
  55770. if (index > -1) {
  55771. this._scene.particleSystems.splice(index, 1);
  55772. }
  55773. // Callback
  55774. this.onDisposeObservable.notifyObservers(this);
  55775. this.onDisposeObservable.clear();
  55776. };
  55777. /**
  55778. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55779. * @param radius The radius of the sphere to emit from
  55780. * @returns the emitter
  55781. */
  55782. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55783. if (radius === void 0) { radius = 1; }
  55784. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55785. this.particleEmitterType = particleEmitter;
  55786. return particleEmitter;
  55787. };
  55788. /**
  55789. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55790. * @param radius The radius of the sphere to emit from
  55791. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55792. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55793. * @returns the emitter
  55794. */
  55795. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55796. if (radius === void 0) { radius = 1; }
  55797. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55798. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55799. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55800. this.particleEmitterType = particleEmitter;
  55801. return particleEmitter;
  55802. };
  55803. /**
  55804. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55805. * @param radius The radius of the cone to emit from
  55806. * @param angle The base angle of the cone
  55807. * @returns the emitter
  55808. */
  55809. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55810. if (radius === void 0) { radius = 1; }
  55811. if (angle === void 0) { angle = Math.PI / 4; }
  55812. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55813. this.particleEmitterType = particleEmitter;
  55814. return particleEmitter;
  55815. };
  55816. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  55817. /**
  55818. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55819. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55820. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55821. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55822. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55823. * @returns the emitter
  55824. */
  55825. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55826. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55827. this.particleEmitterType = particleEmitter;
  55828. this.direction1 = direction1;
  55829. this.direction2 = direction2;
  55830. this.minEmitBox = minEmitBox;
  55831. this.maxEmitBox = maxEmitBox;
  55832. return particleEmitter;
  55833. };
  55834. // Clone
  55835. /**
  55836. * Clones the particle system.
  55837. * @param name The name of the cloned object
  55838. * @param newEmitter The new emitter to use
  55839. * @returns the cloned particle system
  55840. */
  55841. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55842. var custom = null;
  55843. var program = null;
  55844. if (this.customShader != null) {
  55845. program = this.customShader;
  55846. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55847. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55848. }
  55849. else if (this._customEffect) {
  55850. custom = this._customEffect;
  55851. }
  55852. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55853. result.customShader = program;
  55854. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55855. if (newEmitter === undefined) {
  55856. newEmitter = this.emitter;
  55857. }
  55858. result.emitter = newEmitter;
  55859. if (this.particleTexture) {
  55860. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55861. }
  55862. if (!this.preventAutoStart) {
  55863. result.start();
  55864. }
  55865. return result;
  55866. };
  55867. /**
  55868. * Serializes the particle system to a JSON object.
  55869. * @returns the JSON object
  55870. */
  55871. ParticleSystem.prototype.serialize = function () {
  55872. var serializationObject = {};
  55873. ParticleSystem._Serialize(serializationObject, this);
  55874. serializationObject.textureMask = this.textureMask.asArray();
  55875. serializationObject.customShader = this.customShader;
  55876. serializationObject.preventAutoStart = this.preventAutoStart;
  55877. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55878. return serializationObject;
  55879. };
  55880. /** @hidden */
  55881. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  55882. serializationObject.name = particleSystem.name;
  55883. serializationObject.id = particleSystem.id;
  55884. serializationObject.capacity = particleSystem.getCapacity();
  55885. // Emitter
  55886. if (particleSystem.emitter.position) {
  55887. var emitterMesh = particleSystem.emitter;
  55888. serializationObject.emitterId = emitterMesh.id;
  55889. }
  55890. else {
  55891. var emitterPosition = particleSystem.emitter;
  55892. serializationObject.emitter = emitterPosition.asArray();
  55893. }
  55894. // Emitter
  55895. if (particleSystem.particleEmitterType) {
  55896. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  55897. }
  55898. if (particleSystem.particleTexture) {
  55899. serializationObject.textureName = particleSystem.particleTexture.name;
  55900. }
  55901. // Animations
  55902. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  55903. // Particle system
  55904. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  55905. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  55906. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  55907. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  55908. serializationObject.minSize = particleSystem.minSize;
  55909. serializationObject.maxSize = particleSystem.maxSize;
  55910. serializationObject.minScaleX = particleSystem.minScaleX;
  55911. serializationObject.maxScaleX = particleSystem.maxScaleX;
  55912. serializationObject.minScaleY = particleSystem.minScaleY;
  55913. serializationObject.maxScaleY = particleSystem.maxScaleY;
  55914. serializationObject.minEmitPower = particleSystem.minEmitPower;
  55915. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  55916. serializationObject.minLifeTime = particleSystem.minLifeTime;
  55917. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  55918. serializationObject.emitRate = particleSystem.emitRate;
  55919. serializationObject.gravity = particleSystem.gravity.asArray();
  55920. serializationObject.color1 = particleSystem.color1.asArray();
  55921. serializationObject.color2 = particleSystem.color2.asArray();
  55922. serializationObject.colorDead = particleSystem.colorDead.asArray();
  55923. serializationObject.updateSpeed = particleSystem.updateSpeed;
  55924. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  55925. serializationObject.blendMode = particleSystem.blendMode;
  55926. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  55927. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  55928. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  55929. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  55930. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  55931. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  55932. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  55933. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  55934. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  55935. var colorGradients = particleSystem.getColorGradients();
  55936. if (colorGradients) {
  55937. serializationObject.colorGradients = [];
  55938. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  55939. var colorGradient = colorGradients_1[_i];
  55940. var serializedGradient = {
  55941. gradient: colorGradient.gradient,
  55942. color1: colorGradient.color1.asArray()
  55943. };
  55944. if (colorGradient.color2) {
  55945. serializedGradient.color2 = colorGradient.color2.asArray();
  55946. }
  55947. serializationObject.colorGradients.push(serializedGradient);
  55948. }
  55949. }
  55950. var sizeGradients = particleSystem.getSizeGradients();
  55951. if (sizeGradients) {
  55952. serializationObject.sizeGradients = [];
  55953. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  55954. var sizeGradient = sizeGradients_1[_a];
  55955. var serializedGradient = {
  55956. gradient: sizeGradient.gradient,
  55957. factor1: sizeGradient.factor1
  55958. };
  55959. if (sizeGradient.factor2 !== undefined) {
  55960. serializedGradient.factor2 = sizeGradient.factor2;
  55961. }
  55962. serializationObject.sizeGradients.push(serializedGradient);
  55963. }
  55964. }
  55965. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  55966. if (angularSpeedGradients) {
  55967. serializationObject.angularSpeedGradients = [];
  55968. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  55969. var angularSpeedGradient = angularSpeedGradients_1[_b];
  55970. var serializedGradient = {
  55971. gradient: angularSpeedGradient.gradient,
  55972. factor1: angularSpeedGradient.factor1
  55973. };
  55974. if (angularSpeedGradient.factor2 !== undefined) {
  55975. serializedGradient.factor2 = angularSpeedGradient.factor2;
  55976. }
  55977. serializationObject.angularSpeedGradients.push(serializedGradient);
  55978. }
  55979. }
  55980. var velocityGradients = particleSystem.getVelocityGradients();
  55981. if (velocityGradients) {
  55982. serializationObject.velocityGradients = [];
  55983. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  55984. var velocityGradient = velocityGradients_1[_c];
  55985. var serializedGradient = {
  55986. gradient: velocityGradient.gradient,
  55987. factor1: velocityGradient.factor1
  55988. };
  55989. if (velocityGradient.factor2 !== undefined) {
  55990. serializedGradient.factor2 = velocityGradient.factor2;
  55991. }
  55992. serializationObject.velocityGradients.push(serializedGradient);
  55993. }
  55994. }
  55995. };
  55996. /** @hidden */
  55997. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  55998. // Texture
  55999. if (parsedParticleSystem.textureName) {
  56000. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56001. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56002. }
  56003. // Emitter
  56004. if (parsedParticleSystem.emitterId === undefined) {
  56005. particleSystem.emitter = BABYLON.Vector3.Zero();
  56006. }
  56007. else if (parsedParticleSystem.emitterId) {
  56008. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56009. }
  56010. else {
  56011. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56012. }
  56013. // Misc.
  56014. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56015. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56016. }
  56017. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56018. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56019. }
  56020. // Animations
  56021. if (parsedParticleSystem.animations) {
  56022. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56023. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56024. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56025. }
  56026. }
  56027. if (parsedParticleSystem.autoAnimate) {
  56028. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56029. }
  56030. // Particle system
  56031. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56032. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56033. particleSystem.minSize = parsedParticleSystem.minSize;
  56034. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56035. if (parsedParticleSystem.minScaleX) {
  56036. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56037. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56038. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56039. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56040. }
  56041. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56042. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56043. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56044. }
  56045. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56046. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56047. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56048. }
  56049. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56050. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56051. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56052. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56053. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56054. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56055. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56056. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56057. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56058. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56059. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56060. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56061. if (parsedParticleSystem.colorGradients) {
  56062. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56063. var colorGradient = _a[_i];
  56064. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56065. }
  56066. }
  56067. if (parsedParticleSystem.sizeGradients) {
  56068. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56069. var sizeGradient = _c[_b];
  56070. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56071. }
  56072. }
  56073. if (parsedParticleSystem.angularSpeedGradients) {
  56074. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56075. var angularSpeedGradient = _e[_d];
  56076. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56077. }
  56078. }
  56079. if (parsedParticleSystem.velocityGradients) {
  56080. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56081. var velocityGradient = _g[_f];
  56082. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56083. }
  56084. }
  56085. // Emitter
  56086. var emitterType;
  56087. if (parsedParticleSystem.particleEmitterType) {
  56088. switch (parsedParticleSystem.particleEmitterType.type) {
  56089. case "SphereParticleEmitter":
  56090. emitterType = new BABYLON.SphereParticleEmitter();
  56091. break;
  56092. case "SphereDirectedParticleEmitter":
  56093. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56094. break;
  56095. case "ConeEmitter":
  56096. case "ConeParticleEmitter":
  56097. emitterType = new BABYLON.ConeParticleEmitter();
  56098. break;
  56099. case "BoxEmitter":
  56100. case "BoxParticleEmitter":
  56101. default:
  56102. emitterType = new BABYLON.BoxParticleEmitter();
  56103. break;
  56104. }
  56105. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56106. }
  56107. else {
  56108. emitterType = new BABYLON.BoxParticleEmitter();
  56109. emitterType.parse(parsedParticleSystem);
  56110. }
  56111. particleSystem.particleEmitterType = emitterType;
  56112. // Animation sheet
  56113. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56114. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56115. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56116. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56117. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56118. };
  56119. /**
  56120. * Parses a JSON object to create a particle system.
  56121. * @param parsedParticleSystem The JSON object to parse
  56122. * @param scene The scene to create the particle system in
  56123. * @param rootUrl The root url to use to load external dependencies like texture
  56124. * @returns the Parsed particle system
  56125. */
  56126. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56127. var name = parsedParticleSystem.name;
  56128. var custom = null;
  56129. var program = null;
  56130. if (parsedParticleSystem.customShader) {
  56131. program = parsedParticleSystem.customShader;
  56132. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56133. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56134. }
  56135. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56136. particleSystem.customShader = program;
  56137. if (parsedParticleSystem.id) {
  56138. particleSystem.id = parsedParticleSystem.id;
  56139. }
  56140. // Auto start
  56141. if (parsedParticleSystem.preventAutoStart) {
  56142. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56143. }
  56144. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56145. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56146. if (!particleSystem.preventAutoStart) {
  56147. particleSystem.start();
  56148. }
  56149. return particleSystem;
  56150. };
  56151. /**
  56152. * Source color is added to the destination color without alpha affecting the result.
  56153. */
  56154. ParticleSystem.BLENDMODE_ONEONE = 0;
  56155. /**
  56156. * Blend current color and particle color using particle’s alpha.
  56157. */
  56158. ParticleSystem.BLENDMODE_STANDARD = 1;
  56159. /**
  56160. * Add current color and particle color multiplied by particle’s alpha.
  56161. */
  56162. ParticleSystem.BLENDMODE_ADD = 2;
  56163. return ParticleSystem;
  56164. }());
  56165. BABYLON.ParticleSystem = ParticleSystem;
  56166. })(BABYLON || (BABYLON = {}));
  56167. //# sourceMappingURL=babylon.particleSystem.js.map
  56168. var BABYLON;
  56169. (function (BABYLON) {
  56170. /**
  56171. * Particle emitter emitting particles from the inside of a box.
  56172. * It emits the particles randomly between 2 given directions.
  56173. */
  56174. var BoxParticleEmitter = /** @class */ (function () {
  56175. /**
  56176. * Creates a new instance BoxParticleEmitter
  56177. */
  56178. function BoxParticleEmitter() {
  56179. /**
  56180. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56181. */
  56182. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56183. /**
  56184. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56185. */
  56186. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56187. /**
  56188. * 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.
  56189. */
  56190. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56191. /**
  56192. * 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.
  56193. */
  56194. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56195. }
  56196. /**
  56197. * Called by the particle System when the direction is computed for the created particle.
  56198. * @param worldMatrix is the world matrix of the particle system
  56199. * @param directionToUpdate is the direction vector to update with the result
  56200. * @param particle is the particle we are computed the direction for
  56201. */
  56202. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56203. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56204. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56205. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56206. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56207. };
  56208. /**
  56209. * Called by the particle System when the position is computed for the created particle.
  56210. * @param worldMatrix is the world matrix of the particle system
  56211. * @param positionToUpdate is the position vector to update with the result
  56212. * @param particle is the particle we are computed the position for
  56213. */
  56214. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56215. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56216. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56217. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56219. };
  56220. /**
  56221. * Clones the current emitter and returns a copy of it
  56222. * @returns the new emitter
  56223. */
  56224. BoxParticleEmitter.prototype.clone = function () {
  56225. var newOne = new BoxParticleEmitter();
  56226. BABYLON.Tools.DeepCopy(this, newOne);
  56227. return newOne;
  56228. };
  56229. /**
  56230. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56231. * @param effect defines the update shader
  56232. */
  56233. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56234. effect.setVector3("direction1", this.direction1);
  56235. effect.setVector3("direction2", this.direction2);
  56236. effect.setVector3("minEmitBox", this.minEmitBox);
  56237. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56238. };
  56239. /**
  56240. * Returns a string to use to update the GPU particles update shader
  56241. * @returns a string containng the defines string
  56242. */
  56243. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56244. return "#define BOXEMITTER";
  56245. };
  56246. /**
  56247. * Returns the string "BoxParticleEmitter"
  56248. * @returns a string containing the class name
  56249. */
  56250. BoxParticleEmitter.prototype.getClassName = function () {
  56251. return "BoxParticleEmitter";
  56252. };
  56253. /**
  56254. * Serializes the particle system to a JSON object.
  56255. * @returns the JSON object
  56256. */
  56257. BoxParticleEmitter.prototype.serialize = function () {
  56258. var serializationObject = {};
  56259. serializationObject.type = this.getClassName();
  56260. serializationObject.direction1 = this.direction1.asArray();
  56261. serializationObject.direction2 = this.direction2.asArray();
  56262. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56263. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56264. return serializationObject;
  56265. };
  56266. /**
  56267. * Parse properties from a JSON object
  56268. * @param serializationObject defines the JSON object
  56269. */
  56270. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56271. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56272. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56273. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56274. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56275. };
  56276. return BoxParticleEmitter;
  56277. }());
  56278. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56279. })(BABYLON || (BABYLON = {}));
  56280. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56281. var BABYLON;
  56282. (function (BABYLON) {
  56283. /**
  56284. * Particle emitter emitting particles from the inside of a cone.
  56285. * It emits the particles alongside the cone volume from the base to the particle.
  56286. * The emission direction might be randomized.
  56287. */
  56288. var ConeParticleEmitter = /** @class */ (function () {
  56289. /**
  56290. * Creates a new instance ConeParticleEmitter
  56291. * @param radius the radius of the emission cone (1 by default)
  56292. * @param angles the cone base angle (PI by default)
  56293. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56294. */
  56295. function ConeParticleEmitter(radius, angle,
  56296. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56297. directionRandomizer) {
  56298. if (radius === void 0) { radius = 1; }
  56299. if (angle === void 0) { angle = Math.PI; }
  56300. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56301. this.directionRandomizer = directionRandomizer;
  56302. /**
  56303. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56304. */
  56305. this.radiusRange = 1;
  56306. /**
  56307. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56308. */
  56309. this.heightRange = 1;
  56310. this.angle = angle;
  56311. this.radius = radius;
  56312. }
  56313. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56314. /**
  56315. * Gets or sets the radius of the emission cone
  56316. */
  56317. get: function () {
  56318. return this._radius;
  56319. },
  56320. set: function (value) {
  56321. this._radius = value;
  56322. this._buildHeight();
  56323. },
  56324. enumerable: true,
  56325. configurable: true
  56326. });
  56327. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56328. /**
  56329. * Gets or sets the angle of the emission cone
  56330. */
  56331. get: function () {
  56332. return this._angle;
  56333. },
  56334. set: function (value) {
  56335. this._angle = value;
  56336. this._buildHeight();
  56337. },
  56338. enumerable: true,
  56339. configurable: true
  56340. });
  56341. ConeParticleEmitter.prototype._buildHeight = function () {
  56342. if (this._angle !== 0) {
  56343. this._height = this._radius / Math.tan(this._angle / 2);
  56344. }
  56345. else {
  56346. this._height = 1;
  56347. }
  56348. };
  56349. /**
  56350. * Called by the particle System when the direction is computed for the created particle.
  56351. * @param worldMatrix is the world matrix of the particle system
  56352. * @param directionToUpdate is the direction vector to update with the result
  56353. * @param particle is the particle we are computed the direction for
  56354. */
  56355. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56356. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56357. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56358. }
  56359. else {
  56360. // measure the direction Vector from the emitter to the particle.
  56361. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56362. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56363. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56364. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56365. direction.x += randX;
  56366. direction.y += randY;
  56367. direction.z += randZ;
  56368. direction.normalize();
  56369. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56370. }
  56371. };
  56372. /**
  56373. * Called by the particle System when the position is computed for the created particle.
  56374. * @param worldMatrix is the world matrix of the particle system
  56375. * @param positionToUpdate is the position vector to update with the result
  56376. * @param particle is the particle we are computed the position for
  56377. */
  56378. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56379. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56380. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56381. // Better distribution in a cone at normal angles.
  56382. h = 1 - h * h;
  56383. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56384. radius = radius * h;
  56385. var randX = radius * Math.sin(s);
  56386. var randZ = radius * Math.cos(s);
  56387. var randY = h * this._height;
  56388. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56389. };
  56390. /**
  56391. * Clones the current emitter and returns a copy of it
  56392. * @returns the new emitter
  56393. */
  56394. ConeParticleEmitter.prototype.clone = function () {
  56395. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56396. BABYLON.Tools.DeepCopy(this, newOne);
  56397. return newOne;
  56398. };
  56399. /**
  56400. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56401. * @param effect defines the update shader
  56402. */
  56403. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56404. effect.setFloat2("radius", this._radius, this.radiusRange);
  56405. effect.setFloat("coneAngle", this._angle);
  56406. effect.setFloat2("height", this._height, this.heightRange);
  56407. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56408. };
  56409. /**
  56410. * Returns a string to use to update the GPU particles update shader
  56411. * @returns a string containng the defines string
  56412. */
  56413. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56414. return "#define CONEEMITTER";
  56415. };
  56416. /**
  56417. * Returns the string "ConeParticleEmitter"
  56418. * @returns a string containing the class name
  56419. */
  56420. ConeParticleEmitter.prototype.getClassName = function () {
  56421. return "ConeParticleEmitter";
  56422. };
  56423. /**
  56424. * Serializes the particle system to a JSON object.
  56425. * @returns the JSON object
  56426. */
  56427. ConeParticleEmitter.prototype.serialize = function () {
  56428. var serializationObject = {};
  56429. serializationObject.type = this.getClassName();
  56430. serializationObject.radius = this._radius;
  56431. serializationObject.angle = this._angle;
  56432. serializationObject.directionRandomizer = this.directionRandomizer;
  56433. return serializationObject;
  56434. };
  56435. /**
  56436. * Parse properties from a JSON object
  56437. * @param serializationObject defines the JSON object
  56438. */
  56439. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56440. this.radius = serializationObject.radius;
  56441. this.angle = serializationObject.angle;
  56442. this.directionRandomizer = serializationObject.directionRandomizer;
  56443. };
  56444. return ConeParticleEmitter;
  56445. }());
  56446. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56447. })(BABYLON || (BABYLON = {}));
  56448. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56449. var BABYLON;
  56450. (function (BABYLON) {
  56451. /**
  56452. * Particle emitter emitting particles from the inside of a sphere.
  56453. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56454. */
  56455. var SphereParticleEmitter = /** @class */ (function () {
  56456. /**
  56457. * Creates a new instance SphereParticleEmitter
  56458. * @param radius the radius of the emission sphere (1 by default)
  56459. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56460. */
  56461. function SphereParticleEmitter(
  56462. /**
  56463. * The radius of the emission sphere.
  56464. */
  56465. radius,
  56466. /**
  56467. * How much to randomize the particle direction [0-1].
  56468. */
  56469. directionRandomizer) {
  56470. if (radius === void 0) { radius = 1; }
  56471. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56472. this.radius = radius;
  56473. this.directionRandomizer = directionRandomizer;
  56474. /**
  56475. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56476. */
  56477. this.radiusRange = 1;
  56478. }
  56479. /**
  56480. * Called by the particle System when the direction is computed for the created particle.
  56481. * @param worldMatrix is the world matrix of the particle system
  56482. * @param directionToUpdate is the direction vector to update with the result
  56483. * @param particle is the particle we are computed the direction for
  56484. */
  56485. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56486. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56487. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56488. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56489. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56490. direction.x += randX;
  56491. direction.y += randY;
  56492. direction.z += randZ;
  56493. direction.normalize();
  56494. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56495. };
  56496. /**
  56497. * Called by the particle System when the position is computed for the created particle.
  56498. * @param worldMatrix is the world matrix of the particle system
  56499. * @param positionToUpdate is the position vector to update with the result
  56500. * @param particle is the particle we are computed the position for
  56501. */
  56502. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56503. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56504. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56505. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56506. var theta = Math.acos(2 * v - 1);
  56507. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56508. var randY = randRadius * Math.cos(theta);
  56509. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56510. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56511. };
  56512. /**
  56513. * Clones the current emitter and returns a copy of it
  56514. * @returns the new emitter
  56515. */
  56516. SphereParticleEmitter.prototype.clone = function () {
  56517. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56518. BABYLON.Tools.DeepCopy(this, newOne);
  56519. return newOne;
  56520. };
  56521. /**
  56522. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56523. * @param effect defines the update shader
  56524. */
  56525. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56526. effect.setFloat("radius", this.radius);
  56527. effect.setFloat("radiusRange", this.radiusRange);
  56528. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56529. };
  56530. /**
  56531. * Returns a string to use to update the GPU particles update shader
  56532. * @returns a string containng the defines string
  56533. */
  56534. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56535. return "#define SPHEREEMITTER";
  56536. };
  56537. /**
  56538. * Returns the string "SphereParticleEmitter"
  56539. * @returns a string containing the class name
  56540. */
  56541. SphereParticleEmitter.prototype.getClassName = function () {
  56542. return "SphereParticleEmitter";
  56543. };
  56544. /**
  56545. * Serializes the particle system to a JSON object.
  56546. * @returns the JSON object
  56547. */
  56548. SphereParticleEmitter.prototype.serialize = function () {
  56549. var serializationObject = {};
  56550. serializationObject.type = this.getClassName();
  56551. serializationObject.radius = this.radius;
  56552. serializationObject.radiusRange = this.radiusRange;
  56553. serializationObject.directionRandomizer = this.directionRandomizer;
  56554. return serializationObject;
  56555. };
  56556. /**
  56557. * Parse properties from a JSON object
  56558. * @param serializationObject defines the JSON object
  56559. */
  56560. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56561. this.radius = serializationObject.radius;
  56562. this.radiusRange = serializationObject.radiusRange;
  56563. this.directionRandomizer = serializationObject.directionRandomizer;
  56564. };
  56565. return SphereParticleEmitter;
  56566. }());
  56567. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56568. /**
  56569. * Particle emitter emitting particles from the inside of a sphere.
  56570. * It emits the particles randomly between two vectors.
  56571. */
  56572. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56573. __extends(SphereDirectedParticleEmitter, _super);
  56574. /**
  56575. * Creates a new instance SphereDirectedParticleEmitter
  56576. * @param radius the radius of the emission sphere (1 by default)
  56577. * @param direction1 the min limit of the emission direction (up vector by default)
  56578. * @param direction2 the max limit of the emission direction (up vector by default)
  56579. */
  56580. function SphereDirectedParticleEmitter(radius,
  56581. /**
  56582. * The min limit of the emission direction.
  56583. */
  56584. direction1,
  56585. /**
  56586. * The max limit of the emission direction.
  56587. */
  56588. direction2) {
  56589. if (radius === void 0) { radius = 1; }
  56590. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56591. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56592. var _this = _super.call(this, radius) || this;
  56593. _this.direction1 = direction1;
  56594. _this.direction2 = direction2;
  56595. return _this;
  56596. }
  56597. /**
  56598. * Called by the particle System when the direction is computed for the created particle.
  56599. * @param worldMatrix is the world matrix of the particle system
  56600. * @param directionToUpdate is the direction vector to update with the result
  56601. * @param particle is the particle we are computed the direction for
  56602. */
  56603. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56604. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56605. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56606. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56607. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56608. };
  56609. /**
  56610. * Clones the current emitter and returns a copy of it
  56611. * @returns the new emitter
  56612. */
  56613. SphereDirectedParticleEmitter.prototype.clone = function () {
  56614. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56615. BABYLON.Tools.DeepCopy(this, newOne);
  56616. return newOne;
  56617. };
  56618. /**
  56619. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56620. * @param effect defines the update shader
  56621. */
  56622. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56623. effect.setFloat("radius", this.radius);
  56624. effect.setFloat("radiusRange", this.radiusRange);
  56625. effect.setVector3("direction1", this.direction1);
  56626. effect.setVector3("direction2", this.direction2);
  56627. };
  56628. /**
  56629. * Returns a string to use to update the GPU particles update shader
  56630. * @returns a string containng the defines string
  56631. */
  56632. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56633. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56634. };
  56635. /**
  56636. * Returns the string "SphereDirectedParticleEmitter"
  56637. * @returns a string containing the class name
  56638. */
  56639. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56640. return "SphereDirectedParticleEmitter";
  56641. };
  56642. /**
  56643. * Serializes the particle system to a JSON object.
  56644. * @returns the JSON object
  56645. */
  56646. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56647. var serializationObject = _super.prototype.serialize.call(this);
  56648. serializationObject.direction1 = this.direction1.asArray();
  56649. serializationObject.direction2 = this.direction2.asArray();
  56650. return serializationObject;
  56651. };
  56652. /**
  56653. * Parse properties from a JSON object
  56654. * @param serializationObject defines the JSON object
  56655. */
  56656. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56657. _super.prototype.parse.call(this, serializationObject);
  56658. this.direction1.copyFrom(serializationObject.direction1);
  56659. this.direction2.copyFrom(serializationObject.direction2);
  56660. };
  56661. return SphereDirectedParticleEmitter;
  56662. }(SphereParticleEmitter));
  56663. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56664. })(BABYLON || (BABYLON = {}));
  56665. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56666. var BABYLON;
  56667. (function (BABYLON) {
  56668. // Adds the parsers to the scene parsers.
  56669. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  56670. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  56671. if (!individualParser) {
  56672. return;
  56673. }
  56674. // Particles Systems
  56675. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56676. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56677. var parsedParticleSystem = parsedData.particleSystems[index];
  56678. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  56679. }
  56680. }
  56681. });
  56682. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  56683. if (parsedParticleSystem.activeParticleCount) {
  56684. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56685. return ps;
  56686. }
  56687. else {
  56688. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56689. return ps;
  56690. }
  56691. });
  56692. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  56693. if (uniformsNames === void 0) { uniformsNames = []; }
  56694. if (samplers === void 0) { samplers = []; }
  56695. if (defines === void 0) { defines = ""; }
  56696. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  56697. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  56698. if (defines.indexOf(" BILLBOARD") === -1) {
  56699. defines += "\n#define BILLBOARD\n";
  56700. }
  56701. if (samplers.indexOf("diffuseSampler") === -1) {
  56702. samplers.push("diffuseSampler");
  56703. }
  56704. return this.createEffect({
  56705. vertex: "particles",
  56706. fragmentElement: fragmentName
  56707. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  56708. };
  56709. })(BABYLON || (BABYLON = {}));
  56710. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  56711. var BABYLON;
  56712. (function (BABYLON) {
  56713. var ShaderMaterial = /** @class */ (function (_super) {
  56714. __extends(ShaderMaterial, _super);
  56715. function ShaderMaterial(name, scene, shaderPath, options) {
  56716. var _this = _super.call(this, name, scene) || this;
  56717. _this._textures = {};
  56718. _this._textureArrays = {};
  56719. _this._floats = {};
  56720. _this._ints = {};
  56721. _this._floatsArrays = {};
  56722. _this._colors3 = {};
  56723. _this._colors3Arrays = {};
  56724. _this._colors4 = {};
  56725. _this._vectors2 = {};
  56726. _this._vectors3 = {};
  56727. _this._vectors4 = {};
  56728. _this._matrices = {};
  56729. _this._matrices3x3 = {};
  56730. _this._matrices2x2 = {};
  56731. _this._vectors2Arrays = {};
  56732. _this._vectors3Arrays = {};
  56733. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  56734. _this._shaderPath = shaderPath;
  56735. options.needAlphaBlending = options.needAlphaBlending || false;
  56736. options.needAlphaTesting = options.needAlphaTesting || false;
  56737. options.attributes = options.attributes || ["position", "normal", "uv"];
  56738. options.uniforms = options.uniforms || ["worldViewProjection"];
  56739. options.uniformBuffers = options.uniformBuffers || [];
  56740. options.samplers = options.samplers || [];
  56741. options.defines = options.defines || [];
  56742. _this._options = options;
  56743. return _this;
  56744. }
  56745. ShaderMaterial.prototype.getClassName = function () {
  56746. return "ShaderMaterial";
  56747. };
  56748. ShaderMaterial.prototype.needAlphaBlending = function () {
  56749. return this._options.needAlphaBlending;
  56750. };
  56751. ShaderMaterial.prototype.needAlphaTesting = function () {
  56752. return this._options.needAlphaTesting;
  56753. };
  56754. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  56755. if (this._options.uniforms.indexOf(uniformName) === -1) {
  56756. this._options.uniforms.push(uniformName);
  56757. }
  56758. };
  56759. ShaderMaterial.prototype.setTexture = function (name, texture) {
  56760. if (this._options.samplers.indexOf(name) === -1) {
  56761. this._options.samplers.push(name);
  56762. }
  56763. this._textures[name] = texture;
  56764. return this;
  56765. };
  56766. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  56767. if (this._options.samplers.indexOf(name) === -1) {
  56768. this._options.samplers.push(name);
  56769. }
  56770. this._checkUniform(name);
  56771. this._textureArrays[name] = textures;
  56772. return this;
  56773. };
  56774. ShaderMaterial.prototype.setFloat = function (name, value) {
  56775. this._checkUniform(name);
  56776. this._floats[name] = value;
  56777. return this;
  56778. };
  56779. ShaderMaterial.prototype.setInt = function (name, value) {
  56780. this._checkUniform(name);
  56781. this._ints[name] = value;
  56782. return this;
  56783. };
  56784. ShaderMaterial.prototype.setFloats = function (name, value) {
  56785. this._checkUniform(name);
  56786. this._floatsArrays[name] = value;
  56787. return this;
  56788. };
  56789. ShaderMaterial.prototype.setColor3 = function (name, value) {
  56790. this._checkUniform(name);
  56791. this._colors3[name] = value;
  56792. return this;
  56793. };
  56794. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  56795. this._checkUniform(name);
  56796. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  56797. color.toArray(arr, arr.length);
  56798. return arr;
  56799. }, []);
  56800. return this;
  56801. };
  56802. ShaderMaterial.prototype.setColor4 = function (name, value) {
  56803. this._checkUniform(name);
  56804. this._colors4[name] = value;
  56805. return this;
  56806. };
  56807. ShaderMaterial.prototype.setVector2 = function (name, value) {
  56808. this._checkUniform(name);
  56809. this._vectors2[name] = value;
  56810. return this;
  56811. };
  56812. ShaderMaterial.prototype.setVector3 = function (name, value) {
  56813. this._checkUniform(name);
  56814. this._vectors3[name] = value;
  56815. return this;
  56816. };
  56817. ShaderMaterial.prototype.setVector4 = function (name, value) {
  56818. this._checkUniform(name);
  56819. this._vectors4[name] = value;
  56820. return this;
  56821. };
  56822. ShaderMaterial.prototype.setMatrix = function (name, value) {
  56823. this._checkUniform(name);
  56824. this._matrices[name] = value;
  56825. return this;
  56826. };
  56827. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  56828. this._checkUniform(name);
  56829. this._matrices3x3[name] = value;
  56830. return this;
  56831. };
  56832. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  56833. this._checkUniform(name);
  56834. this._matrices2x2[name] = value;
  56835. return this;
  56836. };
  56837. ShaderMaterial.prototype.setArray2 = function (name, value) {
  56838. this._checkUniform(name);
  56839. this._vectors2Arrays[name] = value;
  56840. return this;
  56841. };
  56842. ShaderMaterial.prototype.setArray3 = function (name, value) {
  56843. this._checkUniform(name);
  56844. this._vectors3Arrays[name] = value;
  56845. return this;
  56846. };
  56847. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  56848. if (!mesh) {
  56849. return true;
  56850. }
  56851. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  56852. return false;
  56853. }
  56854. return false;
  56855. };
  56856. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  56857. var scene = this.getScene();
  56858. var engine = scene.getEngine();
  56859. if (!this.checkReadyOnEveryCall) {
  56860. if (this._renderId === scene.getRenderId()) {
  56861. if (this._checkCache(scene, mesh, useInstances)) {
  56862. return true;
  56863. }
  56864. }
  56865. }
  56866. // Instances
  56867. var defines = [];
  56868. var attribs = [];
  56869. var fallbacks = new BABYLON.EffectFallbacks();
  56870. if (useInstances) {
  56871. defines.push("#define INSTANCES");
  56872. }
  56873. for (var index = 0; index < this._options.defines.length; index++) {
  56874. defines.push(this._options.defines[index]);
  56875. }
  56876. for (var index = 0; index < this._options.attributes.length; index++) {
  56877. attribs.push(this._options.attributes[index]);
  56878. }
  56879. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  56880. attribs.push(BABYLON.VertexBuffer.ColorKind);
  56881. defines.push("#define VERTEXCOLOR");
  56882. }
  56883. // Bones
  56884. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56885. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56886. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56887. if (mesh.numBoneInfluencers > 4) {
  56888. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56889. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56890. }
  56891. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56892. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56893. fallbacks.addCPUSkinningFallback(0, mesh);
  56894. if (this._options.uniforms.indexOf("mBones") === -1) {
  56895. this._options.uniforms.push("mBones");
  56896. }
  56897. }
  56898. else {
  56899. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56900. }
  56901. // Textures
  56902. for (var name in this._textures) {
  56903. if (!this._textures[name].isReady()) {
  56904. return false;
  56905. }
  56906. }
  56907. // Alpha test
  56908. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  56909. defines.push("#define ALPHATEST");
  56910. }
  56911. var previousEffect = this._effect;
  56912. var join = defines.join("\n");
  56913. this._effect = engine.createEffect(this._shaderPath, {
  56914. attributes: attribs,
  56915. uniformsNames: this._options.uniforms,
  56916. uniformBuffersNames: this._options.uniformBuffers,
  56917. samplers: this._options.samplers,
  56918. defines: join,
  56919. fallbacks: fallbacks,
  56920. onCompiled: this.onCompiled,
  56921. onError: this.onError
  56922. }, engine);
  56923. if (!this._effect.isReady()) {
  56924. return false;
  56925. }
  56926. if (previousEffect !== this._effect) {
  56927. scene.resetCachedMaterial();
  56928. }
  56929. this._renderId = scene.getRenderId();
  56930. return true;
  56931. };
  56932. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  56933. var scene = this.getScene();
  56934. if (!this._effect) {
  56935. return;
  56936. }
  56937. if (this._options.uniforms.indexOf("world") !== -1) {
  56938. this._effect.setMatrix("world", world);
  56939. }
  56940. if (this._options.uniforms.indexOf("worldView") !== -1) {
  56941. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  56942. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  56943. }
  56944. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  56945. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  56946. }
  56947. };
  56948. ShaderMaterial.prototype.bind = function (world, mesh) {
  56949. // Std values
  56950. this.bindOnlyWorldMatrix(world);
  56951. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  56952. if (this._options.uniforms.indexOf("view") !== -1) {
  56953. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  56954. }
  56955. if (this._options.uniforms.indexOf("projection") !== -1) {
  56956. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  56957. }
  56958. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  56959. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  56960. }
  56961. // Bones
  56962. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  56963. var name;
  56964. // Texture
  56965. for (name in this._textures) {
  56966. this._effect.setTexture(name, this._textures[name]);
  56967. }
  56968. // Texture arrays
  56969. for (name in this._textureArrays) {
  56970. this._effect.setTextureArray(name, this._textureArrays[name]);
  56971. }
  56972. // Int
  56973. for (name in this._ints) {
  56974. this._effect.setInt(name, this._ints[name]);
  56975. }
  56976. // Float
  56977. for (name in this._floats) {
  56978. this._effect.setFloat(name, this._floats[name]);
  56979. }
  56980. // Floats
  56981. for (name in this._floatsArrays) {
  56982. this._effect.setArray(name, this._floatsArrays[name]);
  56983. }
  56984. // Color3
  56985. for (name in this._colors3) {
  56986. this._effect.setColor3(name, this._colors3[name]);
  56987. }
  56988. for (name in this._colors3Arrays) {
  56989. this._effect.setArray3(name, this._colors3Arrays[name]);
  56990. }
  56991. // Color4
  56992. for (name in this._colors4) {
  56993. var color = this._colors4[name];
  56994. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56995. }
  56996. // Vector2
  56997. for (name in this._vectors2) {
  56998. this._effect.setVector2(name, this._vectors2[name]);
  56999. }
  57000. // Vector3
  57001. for (name in this._vectors3) {
  57002. this._effect.setVector3(name, this._vectors3[name]);
  57003. }
  57004. // Vector4
  57005. for (name in this._vectors4) {
  57006. this._effect.setVector4(name, this._vectors4[name]);
  57007. }
  57008. // Matrix
  57009. for (name in this._matrices) {
  57010. this._effect.setMatrix(name, this._matrices[name]);
  57011. }
  57012. // Matrix 3x3
  57013. for (name in this._matrices3x3) {
  57014. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57015. }
  57016. // Matrix 2x2
  57017. for (name in this._matrices2x2) {
  57018. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57019. }
  57020. // Vector2Array
  57021. for (name in this._vectors2Arrays) {
  57022. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57023. }
  57024. // Vector3Array
  57025. for (name in this._vectors3Arrays) {
  57026. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57027. }
  57028. }
  57029. this._afterBind(mesh);
  57030. };
  57031. ShaderMaterial.prototype.getActiveTextures = function () {
  57032. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57033. for (var name in this._textures) {
  57034. activeTextures.push(this._textures[name]);
  57035. }
  57036. for (var name in this._textureArrays) {
  57037. var array = this._textureArrays[name];
  57038. for (var index = 0; index < array.length; index++) {
  57039. activeTextures.push(array[index]);
  57040. }
  57041. }
  57042. return activeTextures;
  57043. };
  57044. ShaderMaterial.prototype.hasTexture = function (texture) {
  57045. if (_super.prototype.hasTexture.call(this, texture)) {
  57046. return true;
  57047. }
  57048. for (var name in this._textures) {
  57049. if (this._textures[name] === texture) {
  57050. return true;
  57051. }
  57052. }
  57053. for (var name in this._textureArrays) {
  57054. var array = this._textureArrays[name];
  57055. for (var index = 0; index < array.length; index++) {
  57056. if (array[index] === texture) {
  57057. return true;
  57058. }
  57059. }
  57060. }
  57061. return false;
  57062. };
  57063. ShaderMaterial.prototype.clone = function (name) {
  57064. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57065. return newShaderMaterial;
  57066. };
  57067. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57068. if (forceDisposeTextures) {
  57069. var name;
  57070. for (name in this._textures) {
  57071. this._textures[name].dispose();
  57072. }
  57073. for (name in this._textureArrays) {
  57074. var array = this._textureArrays[name];
  57075. for (var index = 0; index < array.length; index++) {
  57076. array[index].dispose();
  57077. }
  57078. }
  57079. }
  57080. this._textures = {};
  57081. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57082. };
  57083. ShaderMaterial.prototype.serialize = function () {
  57084. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57085. serializationObject.customType = "BABYLON.ShaderMaterial";
  57086. serializationObject.options = this._options;
  57087. serializationObject.shaderPath = this._shaderPath;
  57088. var name;
  57089. // Texture
  57090. serializationObject.textures = {};
  57091. for (name in this._textures) {
  57092. serializationObject.textures[name] = this._textures[name].serialize();
  57093. }
  57094. // Texture arrays
  57095. serializationObject.textureArrays = {};
  57096. for (name in this._textureArrays) {
  57097. serializationObject.textureArrays[name] = [];
  57098. var array = this._textureArrays[name];
  57099. for (var index = 0; index < array.length; index++) {
  57100. serializationObject.textureArrays[name].push(array[index].serialize());
  57101. }
  57102. }
  57103. // Float
  57104. serializationObject.floats = {};
  57105. for (name in this._floats) {
  57106. serializationObject.floats[name] = this._floats[name];
  57107. }
  57108. // Float s
  57109. serializationObject.FloatArrays = {};
  57110. for (name in this._floatsArrays) {
  57111. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57112. }
  57113. // Color3
  57114. serializationObject.colors3 = {};
  57115. for (name in this._colors3) {
  57116. serializationObject.colors3[name] = this._colors3[name].asArray();
  57117. }
  57118. // Color3 array
  57119. serializationObject.colors3Arrays = {};
  57120. for (name in this._colors3Arrays) {
  57121. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57122. }
  57123. // Color4
  57124. serializationObject.colors4 = {};
  57125. for (name in this._colors4) {
  57126. serializationObject.colors4[name] = this._colors4[name].asArray();
  57127. }
  57128. // Vector2
  57129. serializationObject.vectors2 = {};
  57130. for (name in this._vectors2) {
  57131. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57132. }
  57133. // Vector3
  57134. serializationObject.vectors3 = {};
  57135. for (name in this._vectors3) {
  57136. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57137. }
  57138. // Vector4
  57139. serializationObject.vectors4 = {};
  57140. for (name in this._vectors4) {
  57141. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57142. }
  57143. // Matrix
  57144. serializationObject.matrices = {};
  57145. for (name in this._matrices) {
  57146. serializationObject.matrices[name] = this._matrices[name].asArray();
  57147. }
  57148. // Matrix 3x3
  57149. serializationObject.matrices3x3 = {};
  57150. for (name in this._matrices3x3) {
  57151. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57152. }
  57153. // Matrix 2x2
  57154. serializationObject.matrices2x2 = {};
  57155. for (name in this._matrices2x2) {
  57156. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57157. }
  57158. // Vector2Array
  57159. serializationObject.vectors2Arrays = {};
  57160. for (name in this._vectors2Arrays) {
  57161. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57162. }
  57163. // Vector3Array
  57164. serializationObject.vectors3Arrays = {};
  57165. for (name in this._vectors3Arrays) {
  57166. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57167. }
  57168. return serializationObject;
  57169. };
  57170. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57171. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57172. var name;
  57173. // Texture
  57174. for (name in source.textures) {
  57175. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57176. }
  57177. // Texture arrays
  57178. for (name in source.textureArrays) {
  57179. var array = source.textureArrays[name];
  57180. var textureArray = new Array();
  57181. for (var index = 0; index < array.length; index++) {
  57182. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57183. }
  57184. material.setTextureArray(name, textureArray);
  57185. }
  57186. // Float
  57187. for (name in source.floats) {
  57188. material.setFloat(name, source.floats[name]);
  57189. }
  57190. // Float s
  57191. for (name in source.floatsArrays) {
  57192. material.setFloats(name, source.floatsArrays[name]);
  57193. }
  57194. // Color3
  57195. for (name in source.colors3) {
  57196. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57197. }
  57198. // Color3 arrays
  57199. for (name in source.colors3Arrays) {
  57200. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57201. if (i % 3 === 0) {
  57202. arr.push([num]);
  57203. }
  57204. else {
  57205. arr[arr.length - 1].push(num);
  57206. }
  57207. return arr;
  57208. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57209. material.setColor3Array(name, colors);
  57210. }
  57211. // Color4
  57212. for (name in source.colors4) {
  57213. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57214. }
  57215. // Vector2
  57216. for (name in source.vectors2) {
  57217. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57218. }
  57219. // Vector3
  57220. for (name in source.vectors3) {
  57221. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57222. }
  57223. // Vector4
  57224. for (name in source.vectors4) {
  57225. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57226. }
  57227. // Matrix
  57228. for (name in source.matrices) {
  57229. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57230. }
  57231. // Matrix 3x3
  57232. for (name in source.matrices3x3) {
  57233. material.setMatrix3x3(name, source.matrices3x3[name]);
  57234. }
  57235. // Matrix 2x2
  57236. for (name in source.matrices2x2) {
  57237. material.setMatrix2x2(name, source.matrices2x2[name]);
  57238. }
  57239. // Vector2Array
  57240. for (name in source.vectors2Arrays) {
  57241. material.setArray2(name, source.vectors2Arrays[name]);
  57242. }
  57243. // Vector3Array
  57244. for (name in source.vectors3Arrays) {
  57245. material.setArray3(name, source.vectors3Arrays[name]);
  57246. }
  57247. return material;
  57248. };
  57249. return ShaderMaterial;
  57250. }(BABYLON.Material));
  57251. BABYLON.ShaderMaterial = ShaderMaterial;
  57252. })(BABYLON || (BABYLON = {}));
  57253. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57254. var BABYLON;
  57255. (function (BABYLON) {
  57256. var GroundMesh = /** @class */ (function (_super) {
  57257. __extends(GroundMesh, _super);
  57258. function GroundMesh(name, scene) {
  57259. var _this = _super.call(this, name, scene) || this;
  57260. _this.generateOctree = false;
  57261. return _this;
  57262. }
  57263. GroundMesh.prototype.getClassName = function () {
  57264. return "GroundMesh";
  57265. };
  57266. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57267. get: function () {
  57268. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57269. },
  57270. enumerable: true,
  57271. configurable: true
  57272. });
  57273. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57274. get: function () {
  57275. return this._subdivisionsX;
  57276. },
  57277. enumerable: true,
  57278. configurable: true
  57279. });
  57280. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57281. get: function () {
  57282. return this._subdivisionsY;
  57283. },
  57284. enumerable: true,
  57285. configurable: true
  57286. });
  57287. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57288. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57289. this._subdivisionsX = chunksCount;
  57290. this._subdivisionsY = chunksCount;
  57291. this.subdivide(chunksCount);
  57292. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57293. };
  57294. /**
  57295. * Returns a height (y) value in the Worl system :
  57296. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57297. * Returns the ground y position if (x, z) are outside the ground surface.
  57298. */
  57299. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57300. var world = this.getWorldMatrix();
  57301. var invMat = BABYLON.Tmp.Matrix[5];
  57302. world.invertToRef(invMat);
  57303. var tmpVect = BABYLON.Tmp.Vector3[8];
  57304. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57305. x = tmpVect.x;
  57306. z = tmpVect.z;
  57307. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57308. return this.position.y;
  57309. }
  57310. if (!this._heightQuads || this._heightQuads.length == 0) {
  57311. this._initHeightQuads();
  57312. this._computeHeightQuads();
  57313. }
  57314. var facet = this._getFacetAt(x, z);
  57315. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57316. // return y in the World system
  57317. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57318. return tmpVect.y;
  57319. };
  57320. /**
  57321. * Returns a normalized vector (Vector3) orthogonal to the ground
  57322. * at the ground coordinates (x, z) expressed in the World system.
  57323. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  57324. */
  57325. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  57326. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  57327. this.getNormalAtCoordinatesToRef(x, z, normal);
  57328. return normal;
  57329. };
  57330. /**
  57331. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  57332. * at the ground coordinates (x, z) expressed in the World system.
  57333. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  57334. * Returns the GroundMesh.
  57335. */
  57336. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  57337. var world = this.getWorldMatrix();
  57338. var tmpMat = BABYLON.Tmp.Matrix[5];
  57339. world.invertToRef(tmpMat);
  57340. var tmpVect = BABYLON.Tmp.Vector3[8];
  57341. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  57342. x = tmpVect.x;
  57343. z = tmpVect.z;
  57344. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57345. return this;
  57346. }
  57347. if (!this._heightQuads || this._heightQuads.length == 0) {
  57348. this._initHeightQuads();
  57349. this._computeHeightQuads();
  57350. }
  57351. var facet = this._getFacetAt(x, z);
  57352. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  57353. return this;
  57354. };
  57355. /**
  57356. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  57357. * if the ground has been updated.
  57358. * This can be used in the render loop.
  57359. * Returns the GroundMesh.
  57360. */
  57361. GroundMesh.prototype.updateCoordinateHeights = function () {
  57362. if (!this._heightQuads || this._heightQuads.length == 0) {
  57363. this._initHeightQuads();
  57364. }
  57365. this._computeHeightQuads();
  57366. return this;
  57367. };
  57368. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  57369. GroundMesh.prototype._getFacetAt = function (x, z) {
  57370. // retrieve col and row from x, z coordinates in the ground local system
  57371. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  57372. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  57373. var quad = this._heightQuads[row * this._subdivisionsX + col];
  57374. var facet;
  57375. if (z < quad.slope.x * x + quad.slope.y) {
  57376. facet = quad.facet1;
  57377. }
  57378. else {
  57379. facet = quad.facet2;
  57380. }
  57381. return facet;
  57382. };
  57383. // Creates and populates the heightMap array with "facet" elements :
  57384. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  57385. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57386. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57387. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57388. // Returns the GroundMesh.
  57389. GroundMesh.prototype._initHeightQuads = function () {
  57390. var subdivisionsX = this._subdivisionsX;
  57391. var subdivisionsY = this._subdivisionsY;
  57392. this._heightQuads = new Array();
  57393. for (var row = 0; row < subdivisionsY; row++) {
  57394. for (var col = 0; col < subdivisionsX; col++) {
  57395. 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) };
  57396. this._heightQuads[row * subdivisionsX + col] = quad;
  57397. }
  57398. }
  57399. return this;
  57400. };
  57401. // Compute each quad element values and update the the heightMap array :
  57402. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57403. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57404. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57405. // Returns the GroundMesh.
  57406. GroundMesh.prototype._computeHeightQuads = function () {
  57407. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57408. if (!positions) {
  57409. return this;
  57410. }
  57411. var v1 = BABYLON.Tmp.Vector3[3];
  57412. var v2 = BABYLON.Tmp.Vector3[2];
  57413. var v3 = BABYLON.Tmp.Vector3[1];
  57414. var v4 = BABYLON.Tmp.Vector3[0];
  57415. var v1v2 = BABYLON.Tmp.Vector3[4];
  57416. var v1v3 = BABYLON.Tmp.Vector3[5];
  57417. var v1v4 = BABYLON.Tmp.Vector3[6];
  57418. var norm1 = BABYLON.Tmp.Vector3[7];
  57419. var norm2 = BABYLON.Tmp.Vector3[8];
  57420. var i = 0;
  57421. var j = 0;
  57422. var k = 0;
  57423. var cd = 0; // 2D slope coefficient : z = cd * x + h
  57424. var h = 0;
  57425. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  57426. var d2 = 0;
  57427. var subdivisionsX = this._subdivisionsX;
  57428. var subdivisionsY = this._subdivisionsY;
  57429. for (var row = 0; row < subdivisionsY; row++) {
  57430. for (var col = 0; col < subdivisionsX; col++) {
  57431. i = col * 3;
  57432. j = row * (subdivisionsX + 1) * 3;
  57433. k = (row + 1) * (subdivisionsX + 1) * 3;
  57434. v1.x = positions[j + i];
  57435. v1.y = positions[j + i + 1];
  57436. v1.z = positions[j + i + 2];
  57437. v2.x = positions[j + i + 3];
  57438. v2.y = positions[j + i + 4];
  57439. v2.z = positions[j + i + 5];
  57440. v3.x = positions[k + i];
  57441. v3.y = positions[k + i + 1];
  57442. v3.z = positions[k + i + 2];
  57443. v4.x = positions[k + i + 3];
  57444. v4.y = positions[k + i + 4];
  57445. v4.z = positions[k + i + 5];
  57446. // 2D slope V1V4
  57447. cd = (v4.z - v1.z) / (v4.x - v1.x);
  57448. h = v1.z - cd * v1.x; // v1 belongs to the slope
  57449. // facet equations :
  57450. // we compute each facet normal vector
  57451. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  57452. // we compute the value d by applying the equation to v1 which belongs to the plane
  57453. // then we store the facet equation in a Vector4
  57454. v2.subtractToRef(v1, v1v2);
  57455. v3.subtractToRef(v1, v1v3);
  57456. v4.subtractToRef(v1, v1v4);
  57457. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57458. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57459. norm1.normalize();
  57460. norm2.normalize();
  57461. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57462. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57463. var quad = this._heightQuads[row * subdivisionsX + col];
  57464. quad.slope.copyFromFloats(cd, h);
  57465. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57466. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57467. }
  57468. }
  57469. return this;
  57470. };
  57471. GroundMesh.prototype.serialize = function (serializationObject) {
  57472. _super.prototype.serialize.call(this, serializationObject);
  57473. serializationObject.subdivisionsX = this._subdivisionsX;
  57474. serializationObject.subdivisionsY = this._subdivisionsY;
  57475. serializationObject.minX = this._minX;
  57476. serializationObject.maxX = this._maxX;
  57477. serializationObject.minZ = this._minZ;
  57478. serializationObject.maxZ = this._maxZ;
  57479. serializationObject.width = this._width;
  57480. serializationObject.height = this._height;
  57481. };
  57482. GroundMesh.Parse = function (parsedMesh, scene) {
  57483. var result = new GroundMesh(parsedMesh.name, scene);
  57484. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57485. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57486. result._minX = parsedMesh.minX;
  57487. result._maxX = parsedMesh.maxX;
  57488. result._minZ = parsedMesh.minZ;
  57489. result._maxZ = parsedMesh.maxZ;
  57490. result._width = parsedMesh.width;
  57491. result._height = parsedMesh.height;
  57492. return result;
  57493. };
  57494. return GroundMesh;
  57495. }(BABYLON.Mesh));
  57496. BABYLON.GroundMesh = GroundMesh;
  57497. })(BABYLON || (BABYLON = {}));
  57498. //# sourceMappingURL=babylon.groundMesh.js.map
  57499. var BABYLON;
  57500. (function (BABYLON) {
  57501. /**
  57502. * Creates an instance based on a source mesh.
  57503. */
  57504. var InstancedMesh = /** @class */ (function (_super) {
  57505. __extends(InstancedMesh, _super);
  57506. function InstancedMesh(name, source) {
  57507. var _this = _super.call(this, name, source.getScene()) || this;
  57508. source.instances.push(_this);
  57509. _this._sourceMesh = source;
  57510. _this.position.copyFrom(source.position);
  57511. _this.rotation.copyFrom(source.rotation);
  57512. _this.scaling.copyFrom(source.scaling);
  57513. if (source.rotationQuaternion) {
  57514. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57515. }
  57516. _this.infiniteDistance = source.infiniteDistance;
  57517. _this.setPivotMatrix(source.getPivotMatrix());
  57518. _this.refreshBoundingInfo();
  57519. _this._syncSubMeshes();
  57520. return _this;
  57521. }
  57522. /**
  57523. * Returns the string "InstancedMesh".
  57524. */
  57525. InstancedMesh.prototype.getClassName = function () {
  57526. return "InstancedMesh";
  57527. };
  57528. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  57529. // Methods
  57530. get: function () {
  57531. return this._sourceMesh.receiveShadows;
  57532. },
  57533. enumerable: true,
  57534. configurable: true
  57535. });
  57536. Object.defineProperty(InstancedMesh.prototype, "material", {
  57537. get: function () {
  57538. return this._sourceMesh.material;
  57539. },
  57540. enumerable: true,
  57541. configurable: true
  57542. });
  57543. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  57544. get: function () {
  57545. return this._sourceMesh.visibility;
  57546. },
  57547. enumerable: true,
  57548. configurable: true
  57549. });
  57550. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  57551. get: function () {
  57552. return this._sourceMesh.skeleton;
  57553. },
  57554. enumerable: true,
  57555. configurable: true
  57556. });
  57557. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  57558. get: function () {
  57559. return this._sourceMesh.renderingGroupId;
  57560. },
  57561. set: function (value) {
  57562. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  57563. return;
  57564. }
  57565. //no-op with warning
  57566. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  57567. },
  57568. enumerable: true,
  57569. configurable: true
  57570. });
  57571. /**
  57572. * Returns the total number of vertices (integer).
  57573. */
  57574. InstancedMesh.prototype.getTotalVertices = function () {
  57575. return this._sourceMesh.getTotalVertices();
  57576. };
  57577. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  57578. get: function () {
  57579. return this._sourceMesh;
  57580. },
  57581. enumerable: true,
  57582. configurable: true
  57583. });
  57584. /**
  57585. * Is this node ready to be used/rendered
  57586. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  57587. * @return {boolean} is it ready
  57588. */
  57589. InstancedMesh.prototype.isReady = function (completeCheck) {
  57590. if (completeCheck === void 0) { completeCheck = false; }
  57591. return this._sourceMesh.isReady(completeCheck, true);
  57592. };
  57593. /**
  57594. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  57595. */
  57596. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  57597. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  57598. };
  57599. /**
  57600. * Sets the vertex data of the mesh geometry for the requested `kind`.
  57601. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  57602. * The `data` are either a numeric array either a Float32Array.
  57603. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  57604. * 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).
  57605. * Note that a new underlying VertexBuffer object is created each call.
  57606. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  57607. *
  57608. * Possible `kind` values :
  57609. * - BABYLON.VertexBuffer.PositionKind
  57610. * - BABYLON.VertexBuffer.UVKind
  57611. * - BABYLON.VertexBuffer.UV2Kind
  57612. * - BABYLON.VertexBuffer.UV3Kind
  57613. * - BABYLON.VertexBuffer.UV4Kind
  57614. * - BABYLON.VertexBuffer.UV5Kind
  57615. * - BABYLON.VertexBuffer.UV6Kind
  57616. * - BABYLON.VertexBuffer.ColorKind
  57617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  57620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  57621. *
  57622. * Returns the Mesh.
  57623. */
  57624. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  57625. if (this.sourceMesh) {
  57626. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  57627. }
  57628. return this.sourceMesh;
  57629. };
  57630. /**
  57631. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  57632. * If the mesh has no geometry, it is simply returned as it is.
  57633. * The `data` are either a numeric array either a Float32Array.
  57634. * No new underlying VertexBuffer object is created.
  57635. * 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.
  57636. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  57637. *
  57638. * Possible `kind` values :
  57639. * - BABYLON.VertexBuffer.PositionKind
  57640. * - BABYLON.VertexBuffer.UVKind
  57641. * - BABYLON.VertexBuffer.UV2Kind
  57642. * - BABYLON.VertexBuffer.UV3Kind
  57643. * - BABYLON.VertexBuffer.UV4Kind
  57644. * - BABYLON.VertexBuffer.UV5Kind
  57645. * - BABYLON.VertexBuffer.UV6Kind
  57646. * - BABYLON.VertexBuffer.ColorKind
  57647. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57648. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57649. * - BABYLON.VertexBuffer.MatricesWeightsKind
  57650. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  57651. *
  57652. * Returns the Mesh.
  57653. */
  57654. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  57655. if (this.sourceMesh) {
  57656. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  57657. }
  57658. return this.sourceMesh;
  57659. };
  57660. /**
  57661. * Sets the mesh indices.
  57662. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  57663. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  57664. * This method creates a new index buffer each call.
  57665. * Returns the Mesh.
  57666. */
  57667. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  57668. if (totalVertices === void 0) { totalVertices = null; }
  57669. if (this.sourceMesh) {
  57670. this.sourceMesh.setIndices(indices, totalVertices);
  57671. }
  57672. return this.sourceMesh;
  57673. };
  57674. /**
  57675. * Boolean : True if the mesh owns the requested kind of data.
  57676. */
  57677. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  57678. return this._sourceMesh.isVerticesDataPresent(kind);
  57679. };
  57680. /**
  57681. * Returns an array of indices (IndicesArray).
  57682. */
  57683. InstancedMesh.prototype.getIndices = function () {
  57684. return this._sourceMesh.getIndices();
  57685. };
  57686. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  57687. get: function () {
  57688. return this._sourceMesh._positions;
  57689. },
  57690. enumerable: true,
  57691. configurable: true
  57692. });
  57693. /**
  57694. * Sets a new updated BoundingInfo to the mesh.
  57695. * Returns the mesh.
  57696. */
  57697. InstancedMesh.prototype.refreshBoundingInfo = function () {
  57698. var meshBB = this._sourceMesh.getBoundingInfo();
  57699. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  57700. this._updateBoundingInfo();
  57701. return this;
  57702. };
  57703. InstancedMesh.prototype._preActivate = function () {
  57704. if (this._currentLOD) {
  57705. this._currentLOD._preActivate();
  57706. }
  57707. return this;
  57708. };
  57709. InstancedMesh.prototype._activate = function (renderId) {
  57710. if (this._currentLOD) {
  57711. this._currentLOD._registerInstanceForRenderId(this, renderId);
  57712. }
  57713. return this;
  57714. };
  57715. /**
  57716. * Returns the current associated LOD AbstractMesh.
  57717. */
  57718. InstancedMesh.prototype.getLOD = function (camera) {
  57719. if (!camera) {
  57720. return this;
  57721. }
  57722. var boundingInfo = this.getBoundingInfo();
  57723. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  57724. if (this._currentLOD === this.sourceMesh) {
  57725. return this;
  57726. }
  57727. return this._currentLOD;
  57728. };
  57729. InstancedMesh.prototype._syncSubMeshes = function () {
  57730. this.releaseSubMeshes();
  57731. if (this._sourceMesh.subMeshes) {
  57732. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  57733. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  57734. }
  57735. }
  57736. return this;
  57737. };
  57738. InstancedMesh.prototype._generatePointsArray = function () {
  57739. return this._sourceMesh._generatePointsArray();
  57740. };
  57741. /**
  57742. * Creates a new InstancedMesh from the current mesh.
  57743. * - name (string) : the cloned mesh name
  57744. * - newParent (optional Node) : the optional Node to parent the clone to.
  57745. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  57746. *
  57747. * Returns the clone.
  57748. */
  57749. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57750. var result = this._sourceMesh.createInstance(name);
  57751. // Deep copy
  57752. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  57753. // Bounding info
  57754. this.refreshBoundingInfo();
  57755. // Parent
  57756. if (newParent) {
  57757. result.parent = newParent;
  57758. }
  57759. if (!doNotCloneChildren) {
  57760. // Children
  57761. for (var index = 0; index < this.getScene().meshes.length; index++) {
  57762. var mesh = this.getScene().meshes[index];
  57763. if (mesh.parent === this) {
  57764. mesh.clone(mesh.name, result);
  57765. }
  57766. }
  57767. }
  57768. result.computeWorldMatrix(true);
  57769. return result;
  57770. };
  57771. /**
  57772. * Disposes the InstancedMesh.
  57773. * Returns nothing.
  57774. */
  57775. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  57776. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  57777. // Remove from mesh
  57778. var index = this._sourceMesh.instances.indexOf(this);
  57779. this._sourceMesh.instances.splice(index, 1);
  57780. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  57781. };
  57782. return InstancedMesh;
  57783. }(BABYLON.AbstractMesh));
  57784. BABYLON.InstancedMesh = InstancedMesh;
  57785. })(BABYLON || (BABYLON = {}));
  57786. //# sourceMappingURL=babylon.instancedMesh.js.map
  57787. var BABYLON;
  57788. (function (BABYLON) {
  57789. var LinesMesh = /** @class */ (function (_super) {
  57790. __extends(LinesMesh, _super);
  57791. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  57792. if (scene === void 0) { scene = null; }
  57793. if (parent === void 0) { parent = null; }
  57794. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  57795. _this.useVertexColor = useVertexColor;
  57796. _this.useVertexAlpha = useVertexAlpha;
  57797. _this.color = new BABYLON.Color3(1, 1, 1);
  57798. _this.alpha = 1;
  57799. if (source) {
  57800. _this.color = source.color.clone();
  57801. _this.alpha = source.alpha;
  57802. _this.useVertexColor = source.useVertexColor;
  57803. _this.useVertexAlpha = source.useVertexAlpha;
  57804. }
  57805. _this._intersectionThreshold = 0.1;
  57806. var defines = [];
  57807. var options = {
  57808. attributes: [BABYLON.VertexBuffer.PositionKind],
  57809. uniforms: ["world", "viewProjection"],
  57810. needAlphaBlending: true,
  57811. defines: defines
  57812. };
  57813. if (useVertexAlpha === false) {
  57814. options.needAlphaBlending = false;
  57815. }
  57816. if (!useVertexColor) {
  57817. options.uniforms.push("color");
  57818. }
  57819. else {
  57820. options.defines.push("#define VERTEXCOLOR");
  57821. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  57822. }
  57823. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  57824. return _this;
  57825. }
  57826. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  57827. /**
  57828. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57829. * This margin is expressed in world space coordinates, so its value may vary.
  57830. * Default value is 0.1
  57831. * @returns the intersection Threshold value.
  57832. */
  57833. get: function () {
  57834. return this._intersectionThreshold;
  57835. },
  57836. /**
  57837. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57838. * This margin is expressed in world space coordinates, so its value may vary.
  57839. * @param value the new threshold to apply
  57840. */
  57841. set: function (value) {
  57842. if (this._intersectionThreshold === value) {
  57843. return;
  57844. }
  57845. this._intersectionThreshold = value;
  57846. if (this.geometry) {
  57847. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  57848. }
  57849. },
  57850. enumerable: true,
  57851. configurable: true
  57852. });
  57853. /**
  57854. * Returns the string "LineMesh"
  57855. */
  57856. LinesMesh.prototype.getClassName = function () {
  57857. return "LinesMesh";
  57858. };
  57859. Object.defineProperty(LinesMesh.prototype, "material", {
  57860. get: function () {
  57861. return this._colorShader;
  57862. },
  57863. set: function (value) {
  57864. // Do nothing
  57865. },
  57866. enumerable: true,
  57867. configurable: true
  57868. });
  57869. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  57870. get: function () {
  57871. return false;
  57872. },
  57873. enumerable: true,
  57874. configurable: true
  57875. });
  57876. LinesMesh.prototype.createInstance = function (name) {
  57877. throw new Error("LinesMeshes do not support createInstance.");
  57878. };
  57879. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  57880. if (!this._geometry) {
  57881. return this;
  57882. }
  57883. // VBOs
  57884. this._geometry._bind(this._colorShader.getEffect());
  57885. // Color
  57886. if (!this.useVertexColor) {
  57887. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  57888. }
  57889. return this;
  57890. };
  57891. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  57892. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  57893. return this;
  57894. }
  57895. var engine = this.getScene().getEngine();
  57896. // Draw order
  57897. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  57898. return this;
  57899. };
  57900. LinesMesh.prototype.dispose = function (doNotRecurse) {
  57901. this._colorShader.dispose();
  57902. _super.prototype.dispose.call(this, doNotRecurse);
  57903. };
  57904. /**
  57905. * Returns a new LineMesh object cloned from the current one.
  57906. */
  57907. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57908. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  57909. };
  57910. return LinesMesh;
  57911. }(BABYLON.Mesh));
  57912. BABYLON.LinesMesh = LinesMesh;
  57913. })(BABYLON || (BABYLON = {}));
  57914. //# sourceMappingURL=babylon.linesMesh.js.map
  57915. var BABYLON;
  57916. (function (BABYLON) {
  57917. /**
  57918. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57919. * The underlying implementation relies on an associative array to ensure the best performances.
  57920. * The value can be anything including 'null' but except 'undefined'
  57921. */
  57922. var StringDictionary = /** @class */ (function () {
  57923. function StringDictionary() {
  57924. this._count = 0;
  57925. this._data = {};
  57926. }
  57927. /**
  57928. * This will clear this dictionary and copy the content from the 'source' one.
  57929. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57930. * @param source the dictionary to take the content from and copy to this dictionary
  57931. */
  57932. StringDictionary.prototype.copyFrom = function (source) {
  57933. var _this = this;
  57934. this.clear();
  57935. source.forEach(function (t, v) { return _this.add(t, v); });
  57936. };
  57937. /**
  57938. * Get a value based from its key
  57939. * @param key the given key to get the matching value from
  57940. * @return the value if found, otherwise undefined is returned
  57941. */
  57942. StringDictionary.prototype.get = function (key) {
  57943. var val = this._data[key];
  57944. if (val !== undefined) {
  57945. return val;
  57946. }
  57947. return undefined;
  57948. };
  57949. /**
  57950. * Get a value from its key or add it if it doesn't exist.
  57951. * This method will ensure you that a given key/data will be present in the dictionary.
  57952. * @param key the given key to get the matching value from
  57953. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57954. * The factory will only be invoked if there's no data for the given key.
  57955. * @return the value corresponding to the key.
  57956. */
  57957. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57958. var val = this.get(key);
  57959. if (val !== undefined) {
  57960. return val;
  57961. }
  57962. val = factory(key);
  57963. if (val) {
  57964. this.add(key, val);
  57965. }
  57966. return val;
  57967. };
  57968. /**
  57969. * Get a value from its key if present in the dictionary otherwise add it
  57970. * @param key the key to get the value from
  57971. * @param val if there's no such key/value pair in the dictionary add it with this value
  57972. * @return the value corresponding to the key
  57973. */
  57974. StringDictionary.prototype.getOrAdd = function (key, val) {
  57975. var curVal = this.get(key);
  57976. if (curVal !== undefined) {
  57977. return curVal;
  57978. }
  57979. this.add(key, val);
  57980. return val;
  57981. };
  57982. /**
  57983. * Check if there's a given key in the dictionary
  57984. * @param key the key to check for
  57985. * @return true if the key is present, false otherwise
  57986. */
  57987. StringDictionary.prototype.contains = function (key) {
  57988. return this._data[key] !== undefined;
  57989. };
  57990. /**
  57991. * Add a new key and its corresponding value
  57992. * @param key the key to add
  57993. * @param value the value corresponding to the key
  57994. * @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
  57995. */
  57996. StringDictionary.prototype.add = function (key, value) {
  57997. if (this._data[key] !== undefined) {
  57998. return false;
  57999. }
  58000. this._data[key] = value;
  58001. ++this._count;
  58002. return true;
  58003. };
  58004. StringDictionary.prototype.set = function (key, value) {
  58005. if (this._data[key] === undefined) {
  58006. return false;
  58007. }
  58008. this._data[key] = value;
  58009. return true;
  58010. };
  58011. /**
  58012. * Get the element of the given key and remove it from the dictionary
  58013. * @param key
  58014. */
  58015. StringDictionary.prototype.getAndRemove = function (key) {
  58016. var val = this.get(key);
  58017. if (val !== undefined) {
  58018. delete this._data[key];
  58019. --this._count;
  58020. return val;
  58021. }
  58022. return null;
  58023. };
  58024. /**
  58025. * Remove a key/value from the dictionary.
  58026. * @param key the key to remove
  58027. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58028. */
  58029. StringDictionary.prototype.remove = function (key) {
  58030. if (this.contains(key)) {
  58031. delete this._data[key];
  58032. --this._count;
  58033. return true;
  58034. }
  58035. return false;
  58036. };
  58037. /**
  58038. * Clear the whole content of the dictionary
  58039. */
  58040. StringDictionary.prototype.clear = function () {
  58041. this._data = {};
  58042. this._count = 0;
  58043. };
  58044. Object.defineProperty(StringDictionary.prototype, "count", {
  58045. get: function () {
  58046. return this._count;
  58047. },
  58048. enumerable: true,
  58049. configurable: true
  58050. });
  58051. /**
  58052. * Execute a callback on each key/val of the dictionary.
  58053. * Note that you can remove any element in this dictionary in the callback implementation
  58054. * @param callback the callback to execute on a given key/value pair
  58055. */
  58056. StringDictionary.prototype.forEach = function (callback) {
  58057. for (var cur in this._data) {
  58058. var val = this._data[cur];
  58059. callback(cur, val);
  58060. }
  58061. };
  58062. /**
  58063. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58064. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58065. * Note that you can remove any element in this dictionary in the callback implementation
  58066. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58067. */
  58068. StringDictionary.prototype.first = function (callback) {
  58069. for (var cur in this._data) {
  58070. var val = this._data[cur];
  58071. var res = callback(cur, val);
  58072. if (res) {
  58073. return res;
  58074. }
  58075. }
  58076. return null;
  58077. };
  58078. return StringDictionary;
  58079. }());
  58080. BABYLON.StringDictionary = StringDictionary;
  58081. })(BABYLON || (BABYLON = {}));
  58082. //# sourceMappingURL=babylon.stringDictionary.js.map
  58083. var BABYLON;
  58084. (function (BABYLON) {
  58085. var Debug;
  58086. (function (Debug) {
  58087. /**
  58088. * Class used to render a debug view of a given skeleton
  58089. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58090. */
  58091. var SkeletonViewer = /** @class */ (function () {
  58092. /**
  58093. * Creates a new SkeletonViewer
  58094. * @param skeleton defines the skeleton to render
  58095. * @param mesh defines the mesh attached to the skeleton
  58096. * @param scene defines the hosting scene
  58097. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58098. * @param renderingGroupId defines the rendering group id to use with the viewer
  58099. */
  58100. function SkeletonViewer(
  58101. /** defines the skeleton to render */
  58102. skeleton,
  58103. /** defines the mesh attached to the skeleton */
  58104. mesh, scene,
  58105. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58106. autoUpdateBonesMatrices,
  58107. /** defines the rendering group id to use with the viewer */
  58108. renderingGroupId) {
  58109. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58110. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58111. this.skeleton = skeleton;
  58112. this.mesh = mesh;
  58113. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58114. this.renderingGroupId = renderingGroupId;
  58115. /** Gets or sets the color used to render the skeleton */
  58116. this.color = BABYLON.Color3.White();
  58117. this._debugLines = new Array();
  58118. this._isEnabled = false;
  58119. this._scene = scene;
  58120. this.update();
  58121. this._renderFunction = this.update.bind(this);
  58122. }
  58123. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58124. get: function () {
  58125. return this._isEnabled;
  58126. },
  58127. /** Gets or sets a boolean indicating if the viewer is enabled */
  58128. set: function (value) {
  58129. if (this._isEnabled === value) {
  58130. return;
  58131. }
  58132. this._isEnabled = value;
  58133. if (value) {
  58134. this._scene.registerBeforeRender(this._renderFunction);
  58135. }
  58136. else {
  58137. this._scene.unregisterBeforeRender(this._renderFunction);
  58138. }
  58139. },
  58140. enumerable: true,
  58141. configurable: true
  58142. });
  58143. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58144. if (x === void 0) { x = 0; }
  58145. if (y === void 0) { y = 0; }
  58146. if (z === void 0) { z = 0; }
  58147. var tmat = BABYLON.Tmp.Matrix[0];
  58148. var parentBone = bone.getParent();
  58149. tmat.copyFrom(bone.getLocalMatrix());
  58150. if (x !== 0 || y !== 0 || z !== 0) {
  58151. var tmat2 = BABYLON.Tmp.Matrix[1];
  58152. BABYLON.Matrix.IdentityToRef(tmat2);
  58153. tmat2.m[12] = x;
  58154. tmat2.m[13] = y;
  58155. tmat2.m[14] = z;
  58156. tmat2.multiplyToRef(tmat, tmat);
  58157. }
  58158. if (parentBone) {
  58159. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58160. }
  58161. tmat.multiplyToRef(meshMat, tmat);
  58162. position.x = tmat.m[12];
  58163. position.y = tmat.m[13];
  58164. position.z = tmat.m[14];
  58165. };
  58166. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58167. var len = bones.length;
  58168. var meshPos = this.mesh.position;
  58169. for (var i = 0; i < len; i++) {
  58170. var bone = bones[i];
  58171. var points = this._debugLines[i];
  58172. if (!points) {
  58173. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58174. this._debugLines[i] = points;
  58175. }
  58176. this._getBonePosition(points[0], bone, meshMat);
  58177. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58178. points[0].subtractInPlace(meshPos);
  58179. points[1].subtractInPlace(meshPos);
  58180. }
  58181. };
  58182. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58183. var len = bones.length;
  58184. var boneNum = 0;
  58185. var meshPos = this.mesh.position;
  58186. for (var i = len - 1; i >= 0; i--) {
  58187. var childBone = bones[i];
  58188. var parentBone = childBone.getParent();
  58189. if (!parentBone) {
  58190. continue;
  58191. }
  58192. var points = this._debugLines[boneNum];
  58193. if (!points) {
  58194. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58195. this._debugLines[boneNum] = points;
  58196. }
  58197. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58198. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58199. points[0].subtractInPlace(meshPos);
  58200. points[1].subtractInPlace(meshPos);
  58201. boneNum++;
  58202. }
  58203. };
  58204. /** Update the viewer to sync with current skeleton state */
  58205. SkeletonViewer.prototype.update = function () {
  58206. if (this.autoUpdateBonesMatrices) {
  58207. this.skeleton.computeAbsoluteTransforms();
  58208. }
  58209. if (this.skeleton.bones[0].length === undefined) {
  58210. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58211. }
  58212. else {
  58213. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58214. }
  58215. if (!this._debugMesh) {
  58216. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  58217. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58218. }
  58219. else {
  58220. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58221. }
  58222. this._debugMesh.position.copyFrom(this.mesh.position);
  58223. this._debugMesh.color = this.color;
  58224. };
  58225. /** Release associated resources */
  58226. SkeletonViewer.prototype.dispose = function () {
  58227. if (this._debugMesh) {
  58228. this.isEnabled = false;
  58229. this._debugMesh.dispose();
  58230. this._debugMesh = null;
  58231. }
  58232. };
  58233. return SkeletonViewer;
  58234. }());
  58235. Debug.SkeletonViewer = SkeletonViewer;
  58236. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58237. })(BABYLON || (BABYLON = {}));
  58238. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58239. /**
  58240. * Module Debug contains the (visual) components to debug a scene correctly
  58241. */
  58242. var BABYLON;
  58243. (function (BABYLON) {
  58244. var Debug;
  58245. (function (Debug) {
  58246. /**
  58247. * The Axes viewer will show 3 axes in a specific point in space
  58248. */
  58249. var AxesViewer = /** @class */ (function () {
  58250. /**
  58251. * Creates a new AxesViewer
  58252. * @param scene defines the hosting scene
  58253. * @param scaleLines defines a number used to scale line length (1 by default)
  58254. */
  58255. function AxesViewer(scene, scaleLines) {
  58256. if (scaleLines === void 0) { scaleLines = 1; }
  58257. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58258. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58259. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58260. /**
  58261. * Gets or sets a number used to scale line length
  58262. */
  58263. this.scaleLines = 1;
  58264. this.scaleLines = scaleLines;
  58265. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58266. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58267. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58268. this._xmesh.renderingGroupId = 2;
  58269. this._ymesh.renderingGroupId = 2;
  58270. this._zmesh.renderingGroupId = 2;
  58271. this._xmesh.material.checkReadyOnlyOnce = true;
  58272. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58273. this._ymesh.material.checkReadyOnlyOnce = true;
  58274. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58275. this._zmesh.material.checkReadyOnlyOnce = true;
  58276. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58277. this.scene = scene;
  58278. }
  58279. /**
  58280. * Force the viewer to update
  58281. * @param position defines the position of the viewer
  58282. * @param xaxis defines the x axis of the viewer
  58283. * @param yaxis defines the y axis of the viewer
  58284. * @param zaxis defines the z axis of the viewer
  58285. */
  58286. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58287. var scaleLines = this.scaleLines;
  58288. if (this._xmesh) {
  58289. this._xmesh.position.copyFrom(position);
  58290. }
  58291. if (this._ymesh) {
  58292. this._ymesh.position.copyFrom(position);
  58293. }
  58294. if (this._zmesh) {
  58295. this._zmesh.position.copyFrom(position);
  58296. }
  58297. var point2 = this._xline[1];
  58298. point2.x = xaxis.x * scaleLines;
  58299. point2.y = xaxis.y * scaleLines;
  58300. point2.z = xaxis.z * scaleLines;
  58301. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  58302. point2 = this._yline[1];
  58303. point2.x = yaxis.x * scaleLines;
  58304. point2.y = yaxis.y * scaleLines;
  58305. point2.z = yaxis.z * scaleLines;
  58306. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  58307. point2 = this._zline[1];
  58308. point2.x = zaxis.x * scaleLines;
  58309. point2.y = zaxis.y * scaleLines;
  58310. point2.z = zaxis.z * scaleLines;
  58311. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  58312. };
  58313. /** Releases resources */
  58314. AxesViewer.prototype.dispose = function () {
  58315. if (this._xmesh) {
  58316. this._xmesh.dispose();
  58317. }
  58318. if (this._ymesh) {
  58319. this._ymesh.dispose();
  58320. }
  58321. if (this._zmesh) {
  58322. this._zmesh.dispose();
  58323. }
  58324. this._xmesh = null;
  58325. this._ymesh = null;
  58326. this._zmesh = null;
  58327. this.scene = null;
  58328. };
  58329. return AxesViewer;
  58330. }());
  58331. Debug.AxesViewer = AxesViewer;
  58332. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58333. })(BABYLON || (BABYLON = {}));
  58334. //# sourceMappingURL=babylon.axesViewer.js.map
  58335. var BABYLON;
  58336. (function (BABYLON) {
  58337. var Debug;
  58338. (function (Debug) {
  58339. /**
  58340. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  58341. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  58342. */
  58343. var BoneAxesViewer = /** @class */ (function (_super) {
  58344. __extends(BoneAxesViewer, _super);
  58345. /**
  58346. * Creates a new BoneAxesViewer
  58347. * @param scene defines the hosting scene
  58348. * @param bone defines the target bone
  58349. * @param mesh defines the target mesh
  58350. * @param scaleLines defines a scaling factor for line length (1 by default)
  58351. */
  58352. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58353. if (scaleLines === void 0) { scaleLines = 1; }
  58354. var _this = _super.call(this, scene, scaleLines) || this;
  58355. /** Gets current position */
  58356. _this.pos = BABYLON.Vector3.Zero();
  58357. /** Gets direction of X axis */
  58358. _this.xaxis = BABYLON.Vector3.Zero();
  58359. /** Gets direction of Y axis */
  58360. _this.yaxis = BABYLON.Vector3.Zero();
  58361. /** Gets direction of Z axis */
  58362. _this.zaxis = BABYLON.Vector3.Zero();
  58363. _this.mesh = mesh;
  58364. _this.bone = bone;
  58365. return _this;
  58366. }
  58367. /**
  58368. * Force the viewer to update
  58369. */
  58370. BoneAxesViewer.prototype.update = function () {
  58371. if (!this.mesh || !this.bone) {
  58372. return;
  58373. }
  58374. var bone = this.bone;
  58375. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58376. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58377. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58378. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58379. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58380. };
  58381. /** Releases resources */
  58382. BoneAxesViewer.prototype.dispose = function () {
  58383. if (this.mesh) {
  58384. this.mesh = null;
  58385. this.bone = null;
  58386. _super.prototype.dispose.call(this);
  58387. }
  58388. };
  58389. return BoneAxesViewer;
  58390. }(Debug.AxesViewer));
  58391. Debug.BoneAxesViewer = BoneAxesViewer;
  58392. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58393. })(BABYLON || (BABYLON = {}));
  58394. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58395. var BABYLON;
  58396. (function (BABYLON) {
  58397. var RayHelper = /** @class */ (function () {
  58398. function RayHelper(ray) {
  58399. this.ray = ray;
  58400. }
  58401. RayHelper.CreateAndShow = function (ray, scene, color) {
  58402. var helper = new RayHelper(ray);
  58403. helper.show(scene, color);
  58404. return helper;
  58405. };
  58406. RayHelper.prototype.show = function (scene, color) {
  58407. if (!this._renderFunction && this.ray) {
  58408. var ray = this.ray;
  58409. this._renderFunction = this._render.bind(this);
  58410. this._scene = scene;
  58411. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  58412. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  58413. if (this._renderFunction) {
  58414. this._scene.registerBeforeRender(this._renderFunction);
  58415. }
  58416. }
  58417. if (color && this._renderLine) {
  58418. this._renderLine.color.copyFrom(color);
  58419. }
  58420. };
  58421. RayHelper.prototype.hide = function () {
  58422. if (this._renderFunction && this._scene) {
  58423. this._scene.unregisterBeforeRender(this._renderFunction);
  58424. this._scene = null;
  58425. this._renderFunction = null;
  58426. if (this._renderLine) {
  58427. this._renderLine.dispose();
  58428. this._renderLine = null;
  58429. }
  58430. this._renderPoints = [];
  58431. }
  58432. };
  58433. RayHelper.prototype._render = function () {
  58434. var ray = this.ray;
  58435. if (!ray) {
  58436. return;
  58437. }
  58438. var point = this._renderPoints[1];
  58439. var len = Math.min(ray.length, 1000000);
  58440. point.copyFrom(ray.direction);
  58441. point.scaleInPlace(len);
  58442. point.addInPlace(ray.origin);
  58443. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  58444. };
  58445. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  58446. this._attachedToMesh = mesh;
  58447. var ray = this.ray;
  58448. if (!ray) {
  58449. return;
  58450. }
  58451. if (!ray.direction) {
  58452. ray.direction = BABYLON.Vector3.Zero();
  58453. }
  58454. if (!ray.origin) {
  58455. ray.origin = BABYLON.Vector3.Zero();
  58456. }
  58457. if (length) {
  58458. ray.length = length;
  58459. }
  58460. if (!meshSpaceOrigin) {
  58461. meshSpaceOrigin = BABYLON.Vector3.Zero();
  58462. }
  58463. if (!meshSpaceDirection) {
  58464. // -1 so that this will work with Mesh.lookAt
  58465. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  58466. }
  58467. if (!this._meshSpaceDirection) {
  58468. this._meshSpaceDirection = meshSpaceDirection.clone();
  58469. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  58470. }
  58471. else {
  58472. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  58473. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  58474. }
  58475. if (!this._updateToMeshFunction) {
  58476. this._updateToMeshFunction = this._updateToMesh.bind(this);
  58477. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  58478. }
  58479. this._updateToMesh();
  58480. };
  58481. RayHelper.prototype.detachFromMesh = function () {
  58482. if (this._attachedToMesh) {
  58483. if (this._updateToMeshFunction) {
  58484. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  58485. }
  58486. this._attachedToMesh = null;
  58487. this._updateToMeshFunction = null;
  58488. }
  58489. };
  58490. RayHelper.prototype._updateToMesh = function () {
  58491. var ray = this.ray;
  58492. if (!this._attachedToMesh || !ray) {
  58493. return;
  58494. }
  58495. if (this._attachedToMesh._isDisposed) {
  58496. this.detachFromMesh();
  58497. return;
  58498. }
  58499. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  58500. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  58501. };
  58502. RayHelper.prototype.dispose = function () {
  58503. this.hide();
  58504. this.detachFromMesh();
  58505. this.ray = null;
  58506. };
  58507. return RayHelper;
  58508. }());
  58509. BABYLON.RayHelper = RayHelper;
  58510. })(BABYLON || (BABYLON = {}));
  58511. //# sourceMappingURL=babylon.rayHelper.js.map
  58512. var BABYLON;
  58513. (function (BABYLON) {
  58514. // load the inspector using require, if not present in the global namespace.
  58515. var DebugLayer = /** @class */ (function () {
  58516. function DebugLayer(scene) {
  58517. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58518. this.onPropertyChangedObservable = new BABYLON.Observable();
  58519. this._scene = scene;
  58520. }
  58521. /** Creates the inspector window. */
  58522. DebugLayer.prototype._createInspector = function (config) {
  58523. if (config === void 0) { config = {}; }
  58524. var popup = config.popup || false;
  58525. var initialTab = config.initialTab || 0;
  58526. var parentElement = config.parentElement || null;
  58527. if (!this._inspector) {
  58528. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58529. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  58530. } // else nothing to do as instance is already created
  58531. };
  58532. DebugLayer.prototype.isVisible = function () {
  58533. if (!this._inspector) {
  58534. return false;
  58535. }
  58536. return true;
  58537. };
  58538. DebugLayer.prototype.hide = function () {
  58539. if (this._inspector) {
  58540. try {
  58541. this._inspector.dispose();
  58542. }
  58543. catch (e) {
  58544. // If the inspector has been removed directly from the inspector tool
  58545. }
  58546. this.onPropertyChangedObservable.clear();
  58547. this._inspector = null;
  58548. }
  58549. };
  58550. /**
  58551. *
  58552. * Launch the debugLayer.
  58553. *
  58554. * initialTab:
  58555. * | Value | Tab Name |
  58556. * | --- | --- |
  58557. * | 0 | Scene |
  58558. * | 1 | Console |
  58559. * | 2 | Stats |
  58560. * | 3 | Textures |
  58561. * | 4 | Mesh |
  58562. * | 5 | Light |
  58563. * | 6 | Material |
  58564. * | 7 | GLTF |
  58565. * | 8 | GUI |
  58566. * | 9 | Physics |
  58567. * | 10 | Camera |
  58568. * | 11 | Audio |
  58569. *
  58570. */
  58571. DebugLayer.prototype.show = function (config) {
  58572. if (config === void 0) { config = {}; }
  58573. if (typeof this.BJSINSPECTOR == 'undefined') {
  58574. // Load inspector and add it to the DOM
  58575. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  58576. }
  58577. else {
  58578. // Otherwise creates the inspector
  58579. this._createInspector(config);
  58580. }
  58581. };
  58582. /**
  58583. * Gets the active tab
  58584. * @return the index of the active tab or -1 if the inspector is hidden
  58585. */
  58586. DebugLayer.prototype.getActiveTab = function () {
  58587. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  58588. };
  58589. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  58590. return DebugLayer;
  58591. }());
  58592. BABYLON.DebugLayer = DebugLayer;
  58593. })(BABYLON || (BABYLON = {}));
  58594. //# sourceMappingURL=babylon.debugLayer.js.map
  58595. var BABYLON;
  58596. (function (BABYLON) {
  58597. var Debug;
  58598. (function (Debug) {
  58599. /**
  58600. * Used to show the physics impostor around the specific mesh
  58601. */
  58602. var PhysicsViewer = /** @class */ (function () {
  58603. /**
  58604. * Creates a new PhysicsViewer
  58605. * @param scene defines the hosting scene
  58606. */
  58607. function PhysicsViewer(scene) {
  58608. /** @hidden */
  58609. this._impostors = [];
  58610. /** @hidden */
  58611. this._meshes = [];
  58612. /** @hidden */
  58613. this._numMeshes = 0;
  58614. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58615. var physicEngine = this._scene.getPhysicsEngine();
  58616. if (physicEngine) {
  58617. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  58618. }
  58619. }
  58620. /** @hidden */
  58621. PhysicsViewer.prototype._updateDebugMeshes = function () {
  58622. var plugin = this._physicsEnginePlugin;
  58623. for (var i = 0; i < this._numMeshes; i++) {
  58624. var impostor = this._impostors[i];
  58625. if (!impostor) {
  58626. continue;
  58627. }
  58628. if (impostor.isDisposed) {
  58629. this.hideImpostor(this._impostors[i--]);
  58630. }
  58631. else {
  58632. var mesh = this._meshes[i];
  58633. if (mesh && plugin) {
  58634. plugin.syncMeshWithImpostor(mesh, impostor);
  58635. }
  58636. }
  58637. }
  58638. };
  58639. /**
  58640. * Renders a specified physic impostor
  58641. * @param impostor defines the impostor to render
  58642. */
  58643. PhysicsViewer.prototype.showImpostor = function (impostor) {
  58644. if (!this._scene) {
  58645. return;
  58646. }
  58647. for (var i = 0; i < this._numMeshes; i++) {
  58648. if (this._impostors[i] == impostor) {
  58649. return;
  58650. }
  58651. }
  58652. var debugMesh = this._getDebugMesh(impostor, this._scene);
  58653. if (debugMesh) {
  58654. this._impostors[this._numMeshes] = impostor;
  58655. this._meshes[this._numMeshes] = debugMesh;
  58656. if (this._numMeshes === 0) {
  58657. this._renderFunction = this._updateDebugMeshes.bind(this);
  58658. this._scene.registerBeforeRender(this._renderFunction);
  58659. }
  58660. this._numMeshes++;
  58661. }
  58662. };
  58663. /**
  58664. * Hides a specified physic impostor
  58665. * @param impostor defines the impostor to hide
  58666. */
  58667. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  58668. if (!impostor || !this._scene) {
  58669. return;
  58670. }
  58671. var removed = false;
  58672. for (var i = 0; i < this._numMeshes; i++) {
  58673. if (this._impostors[i] == impostor) {
  58674. var mesh = this._meshes[i];
  58675. if (!mesh) {
  58676. continue;
  58677. }
  58678. this._scene.removeMesh(mesh);
  58679. mesh.dispose();
  58680. this._numMeshes--;
  58681. if (this._numMeshes > 0) {
  58682. this._meshes[i] = this._meshes[this._numMeshes];
  58683. this._impostors[i] = this._impostors[this._numMeshes];
  58684. this._meshes[this._numMeshes] = null;
  58685. this._impostors[this._numMeshes] = null;
  58686. }
  58687. else {
  58688. this._meshes[0] = null;
  58689. this._impostors[0] = null;
  58690. }
  58691. removed = true;
  58692. break;
  58693. }
  58694. }
  58695. if (removed && this._numMeshes === 0) {
  58696. this._scene.unregisterBeforeRender(this._renderFunction);
  58697. }
  58698. };
  58699. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  58700. if (!this._debugMaterial) {
  58701. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  58702. this._debugMaterial.wireframe = true;
  58703. }
  58704. return this._debugMaterial;
  58705. };
  58706. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  58707. if (!this._debugBoxMesh) {
  58708. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  58709. this._debugBoxMesh.renderingGroupId = 1;
  58710. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  58711. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  58712. scene.removeMesh(this._debugBoxMesh);
  58713. }
  58714. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  58715. };
  58716. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  58717. if (!this._debugSphereMesh) {
  58718. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  58719. this._debugSphereMesh.renderingGroupId = 1;
  58720. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  58721. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  58722. scene.removeMesh(this._debugSphereMesh);
  58723. }
  58724. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  58725. };
  58726. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  58727. var mesh = null;
  58728. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  58729. mesh = this._getDebugBoxMesh(scene);
  58730. impostor.getBoxSizeToRef(mesh.scaling);
  58731. }
  58732. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  58733. mesh = this._getDebugSphereMesh(scene);
  58734. var radius = impostor.getRadius();
  58735. mesh.scaling.x = radius * 2;
  58736. mesh.scaling.y = radius * 2;
  58737. mesh.scaling.z = radius * 2;
  58738. }
  58739. return mesh;
  58740. };
  58741. /** Releases all resources */
  58742. PhysicsViewer.prototype.dispose = function () {
  58743. for (var i = 0; i < this._numMeshes; i++) {
  58744. this.hideImpostor(this._impostors[i]);
  58745. }
  58746. if (this._debugBoxMesh) {
  58747. this._debugBoxMesh.dispose();
  58748. }
  58749. if (this._debugSphereMesh) {
  58750. this._debugSphereMesh.dispose();
  58751. }
  58752. if (this._debugMaterial) {
  58753. this._debugMaterial.dispose();
  58754. }
  58755. this._impostors.length = 0;
  58756. this._scene = null;
  58757. this._physicsEnginePlugin = null;
  58758. };
  58759. return PhysicsViewer;
  58760. }());
  58761. Debug.PhysicsViewer = PhysicsViewer;
  58762. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58763. })(BABYLON || (BABYLON = {}));
  58764. //# sourceMappingURL=babylon.physicsViewer.js.map
  58765. var BABYLON;
  58766. (function (BABYLON) {
  58767. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  58768. get: function () {
  58769. return this._forceShowBoundingBoxes || false;
  58770. },
  58771. set: function (value) {
  58772. this._forceShowBoundingBoxes = value;
  58773. // Lazyly creates a BB renderer if needed.
  58774. if (value) {
  58775. this.getBoundingBoxRenderer();
  58776. }
  58777. },
  58778. enumerable: true,
  58779. configurable: true
  58780. });
  58781. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  58782. if (!this._boundingBoxRenderer) {
  58783. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  58784. }
  58785. return this._boundingBoxRenderer;
  58786. };
  58787. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  58788. get: function () {
  58789. return this._showBoundingBox || false;
  58790. },
  58791. set: function (value) {
  58792. this._showBoundingBox = value;
  58793. // Lazyly creates a BB renderer if needed.
  58794. if (value) {
  58795. this.getScene().getBoundingBoxRenderer();
  58796. }
  58797. },
  58798. enumerable: true,
  58799. configurable: true
  58800. });
  58801. var BoundingBoxRenderer = /** @class */ (function () {
  58802. function BoundingBoxRenderer(scene) {
  58803. /**
  58804. * The component name helpfull to identify the component in the list of scene components.
  58805. */
  58806. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  58807. this.frontColor = new BABYLON.Color3(1, 1, 1);
  58808. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  58809. this.showBackLines = true;
  58810. this.renderList = new BABYLON.SmartArray(32);
  58811. this._vertexBuffers = {};
  58812. this.scene = scene;
  58813. scene._addComponent(this);
  58814. }
  58815. /**
  58816. * Registers the component in a given scene
  58817. */
  58818. BoundingBoxRenderer.prototype.register = function () {
  58819. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  58820. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  58821. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  58822. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  58823. };
  58824. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  58825. if (mesh.showSubMeshesBoundingBox) {
  58826. var boundingInfo = subMesh.getBoundingInfo();
  58827. if (boundingInfo !== null && boundingInfo !== undefined) {
  58828. this.renderList.push(boundingInfo.boundingBox);
  58829. }
  58830. }
  58831. };
  58832. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  58833. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  58834. var boundingInfo = sourceMesh.getBoundingInfo();
  58835. this.renderList.push(boundingInfo.boundingBox);
  58836. }
  58837. };
  58838. BoundingBoxRenderer.prototype._prepareRessources = function () {
  58839. if (this._colorShader) {
  58840. return;
  58841. }
  58842. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  58843. attributes: [BABYLON.VertexBuffer.PositionKind],
  58844. uniforms: ["world", "viewProjection", "color"]
  58845. });
  58846. var engine = this.scene.getEngine();
  58847. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  58848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  58849. this._createIndexBuffer();
  58850. };
  58851. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  58852. var engine = this.scene.getEngine();
  58853. 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]);
  58854. };
  58855. /**
  58856. * Rebuilds the elements related to this component in case of
  58857. * context lost for instance.
  58858. */
  58859. BoundingBoxRenderer.prototype.rebuild = function () {
  58860. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58861. if (vb) {
  58862. vb._rebuild();
  58863. }
  58864. this._createIndexBuffer();
  58865. };
  58866. BoundingBoxRenderer.prototype.reset = function () {
  58867. this.renderList.reset();
  58868. };
  58869. BoundingBoxRenderer.prototype.render = function () {
  58870. if (this.renderList.length === 0) {
  58871. return;
  58872. }
  58873. this._prepareRessources();
  58874. if (!this._colorShader.isReady()) {
  58875. return;
  58876. }
  58877. var engine = this.scene.getEngine();
  58878. engine.setDepthWrite(false);
  58879. this._colorShader._preBind();
  58880. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  58881. var boundingBox = this.renderList.data[boundingBoxIndex];
  58882. var min = boundingBox.minimum;
  58883. var max = boundingBox.maximum;
  58884. var diff = max.subtract(min);
  58885. var median = min.add(diff.scale(0.5));
  58886. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  58887. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  58888. .multiply(boundingBox.getWorldMatrix());
  58889. // VBOs
  58890. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  58891. if (this.showBackLines) {
  58892. // Back
  58893. engine.setDepthFunctionToGreaterOrEqual();
  58894. this.scene.resetCachedMaterial();
  58895. this._colorShader.setColor4("color", this.backColor.toColor4());
  58896. this._colorShader.bind(worldMatrix);
  58897. // Draw order
  58898. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  58899. }
  58900. // Front
  58901. engine.setDepthFunctionToLess();
  58902. this.scene.resetCachedMaterial();
  58903. this._colorShader.setColor4("color", this.frontColor.toColor4());
  58904. this._colorShader.bind(worldMatrix);
  58905. // Draw order
  58906. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  58907. }
  58908. this._colorShader.unbind();
  58909. engine.setDepthFunctionToLessOrEqual();
  58910. engine.setDepthWrite(true);
  58911. };
  58912. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  58913. this._prepareRessources();
  58914. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  58915. return;
  58916. }
  58917. var engine = this.scene.getEngine();
  58918. engine.setDepthWrite(false);
  58919. engine.setColorWrite(false);
  58920. this._colorShader._preBind();
  58921. var boundingBox = mesh._boundingInfo.boundingBox;
  58922. var min = boundingBox.minimum;
  58923. var max = boundingBox.maximum;
  58924. var diff = max.subtract(min);
  58925. var median = min.add(diff.scale(0.5));
  58926. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  58927. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  58928. .multiply(boundingBox.getWorldMatrix());
  58929. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  58930. engine.setDepthFunctionToLess();
  58931. this.scene.resetCachedMaterial();
  58932. this._colorShader.bind(worldMatrix);
  58933. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  58934. this._colorShader.unbind();
  58935. engine.setDepthFunctionToLessOrEqual();
  58936. engine.setDepthWrite(true);
  58937. engine.setColorWrite(true);
  58938. };
  58939. BoundingBoxRenderer.prototype.dispose = function () {
  58940. if (!this._colorShader) {
  58941. return;
  58942. }
  58943. this.renderList.dispose();
  58944. this._colorShader.dispose();
  58945. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58946. if (buffer) {
  58947. buffer.dispose();
  58948. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58949. }
  58950. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  58951. };
  58952. return BoundingBoxRenderer;
  58953. }());
  58954. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  58955. })(BABYLON || (BABYLON = {}));
  58956. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  58957. var BABYLON;
  58958. (function (BABYLON) {
  58959. BABYLON.Engine.prototype.createTransformFeedback = function () {
  58960. return this._gl.createTransformFeedback();
  58961. };
  58962. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  58963. this._gl.deleteTransformFeedback(value);
  58964. };
  58965. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  58966. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  58967. };
  58968. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  58969. if (usePoints === void 0) { usePoints = true; }
  58970. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  58971. };
  58972. BABYLON.Engine.prototype.endTransformFeedback = function () {
  58973. this._gl.endTransformFeedback();
  58974. };
  58975. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  58976. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  58977. };
  58978. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  58979. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  58980. };
  58981. })(BABYLON || (BABYLON = {}));
  58982. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  58983. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58984. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58985. s = arguments[i];
  58986. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58987. t[p] = s[p];
  58988. }
  58989. return t;
  58990. };
  58991. var BABYLON;
  58992. (function (BABYLON) {
  58993. /**
  58994. * This represents a GPU particle system in Babylon
  58995. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  58996. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  58997. */
  58998. var GPUParticleSystem = /** @class */ (function () {
  58999. /**
  59000. * Instantiates a GPU particle system.
  59001. * 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.
  59002. * @param name The name of the particle system
  59003. * @param options The options used to create the system
  59004. * @param scene The scene the particle system belongs to
  59005. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59006. */
  59007. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59008. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59009. /**
  59010. * The emitter represents the Mesh or position we are attaching the particle system to.
  59011. */
  59012. this.emitter = null;
  59013. /**
  59014. * The rendering group used by the Particle system to chose when to render.
  59015. */
  59016. this.renderingGroupId = 0;
  59017. /**
  59018. * The layer mask we are rendering the particles through.
  59019. */
  59020. this.layerMask = 0x0FFFFFFF;
  59021. this._accumulatedCount = 0;
  59022. this._targetIndex = 0;
  59023. this._currentRenderId = -1;
  59024. this._started = false;
  59025. this._stopped = false;
  59026. this._timeDelta = 0;
  59027. this._attributesStrideSize = 21;
  59028. this._actualFrame = 0;
  59029. this._rawTextureWidth = 256;
  59030. /**
  59031. * List of animations used by the particle system.
  59032. */
  59033. this.animations = [];
  59034. /**
  59035. * An event triggered when the system is disposed.
  59036. */
  59037. this.onDisposeObservable = new BABYLON.Observable();
  59038. /**
  59039. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59040. */
  59041. this.updateSpeed = 0.01;
  59042. /**
  59043. * The amount of time the particle system is running (depends of the overall update speed).
  59044. */
  59045. this.targetStopDuration = 0;
  59046. /**
  59047. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59048. */
  59049. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59050. /**
  59051. * Minimum life time of emitting particles.
  59052. */
  59053. this.minLifeTime = 1;
  59054. /**
  59055. * Maximum life time of emitting particles.
  59056. */
  59057. this.maxLifeTime = 1;
  59058. /**
  59059. * Minimum Size of emitting particles.
  59060. */
  59061. this.minSize = 1;
  59062. /**
  59063. * Maximum Size of emitting particles.
  59064. */
  59065. this.maxSize = 1;
  59066. /**
  59067. * Minimum scale of emitting particles on X axis.
  59068. */
  59069. this.minScaleX = 1;
  59070. /**
  59071. * Maximum scale of emitting particles on X axis.
  59072. */
  59073. this.maxScaleX = 1;
  59074. /**
  59075. * Minimum scale of emitting particles on Y axis.
  59076. */
  59077. this.minScaleY = 1;
  59078. /**
  59079. * Maximum scale of emitting particles on Y axis.
  59080. */
  59081. this.maxScaleY = 1;
  59082. /**
  59083. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59084. */
  59085. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59086. /**
  59087. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59088. */
  59089. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59090. /**
  59091. * Color the particle will have at the end of its lifetime.
  59092. */
  59093. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59094. /**
  59095. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59096. */
  59097. this.emitRate = 100;
  59098. /**
  59099. * You can use gravity if you want to give an orientation to your particles.
  59100. */
  59101. this.gravity = BABYLON.Vector3.Zero();
  59102. /**
  59103. * Minimum power of emitting particles.
  59104. */
  59105. this.minEmitPower = 1;
  59106. /**
  59107. * Maximum power of emitting particles.
  59108. */
  59109. this.maxEmitPower = 1;
  59110. /**
  59111. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59112. */
  59113. this.minAngularSpeed = 0;
  59114. /**
  59115. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59116. */
  59117. this.maxAngularSpeed = 0;
  59118. /**
  59119. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59120. * to override the particles.
  59121. */
  59122. this.forceDepthWrite = false;
  59123. this._preWarmDone = false;
  59124. /** 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 */
  59125. this.preWarmCycles = 0;
  59126. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59127. this.preWarmStepOffset = 1;
  59128. /**
  59129. * Gets or sets the minimal initial rotation in radians.
  59130. */
  59131. this.minInitialRotation = 0;
  59132. /**
  59133. * Gets or sets the maximal initial rotation in radians.
  59134. */
  59135. this.maxInitialRotation = 0;
  59136. /**
  59137. * 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)
  59138. */
  59139. this.spriteCellChangeSpeed = 1;
  59140. /**
  59141. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59142. */
  59143. this.startSpriteCellID = 0;
  59144. /**
  59145. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59146. */
  59147. this.endSpriteCellID = 0;
  59148. /**
  59149. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59150. */
  59151. this.spriteCellWidth = 0;
  59152. /**
  59153. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59154. */
  59155. this.spriteCellHeight = 0;
  59156. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59157. this.translationPivot = new BABYLON.Vector2(0, 0);
  59158. /**
  59159. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59160. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59161. */
  59162. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59163. this._isBillboardBased = true;
  59164. this._colorGradients = null;
  59165. this._angularSpeedGradients = null;
  59166. this._sizeGradients = null;
  59167. this._velocityGradients = null;
  59168. this.id = name;
  59169. this.name = name;
  59170. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59171. this._engine = this._scene.getEngine();
  59172. if (!options.randomTextureSize) {
  59173. delete options.randomTextureSize;
  59174. }
  59175. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  59176. var optionsAsNumber = options;
  59177. if (isFinite(optionsAsNumber)) {
  59178. fullOptions.capacity = optionsAsNumber;
  59179. }
  59180. this._capacity = fullOptions.capacity;
  59181. this._activeCount = fullOptions.capacity;
  59182. this._currentActiveCount = 0;
  59183. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59184. this._scene.particleSystems.push(this);
  59185. this._updateEffectOptions = {
  59186. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  59187. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  59188. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  59189. "angleRange", "radiusRange", "cellInfos"],
  59190. uniformBuffersNames: [],
  59191. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  59192. defines: "",
  59193. fallbacks: null,
  59194. onCompiled: null,
  59195. onError: null,
  59196. indexParameters: null,
  59197. maxSimultaneousLights: 0,
  59198. transformFeedbackVaryings: []
  59199. };
  59200. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59201. // Random data
  59202. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  59203. var d = [];
  59204. for (var i = 0; i < maxTextureSize; ++i) {
  59205. d.push(Math.random());
  59206. d.push(Math.random());
  59207. d.push(Math.random());
  59208. d.push(Math.random());
  59209. }
  59210. 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);
  59211. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59212. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59213. d = [];
  59214. for (var i = 0; i < maxTextureSize; ++i) {
  59215. d.push(Math.random());
  59216. d.push(Math.random());
  59217. d.push(Math.random());
  59218. d.push(Math.random());
  59219. }
  59220. 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);
  59221. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59222. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59223. this._randomTextureSize = maxTextureSize;
  59224. }
  59225. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  59226. /**
  59227. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  59228. */
  59229. get: function () {
  59230. if (!BABYLON.Engine.LastCreatedEngine) {
  59231. return false;
  59232. }
  59233. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  59234. },
  59235. enumerable: true,
  59236. configurable: true
  59237. });
  59238. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  59239. /**
  59240. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59241. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59242. */
  59243. get: function () {
  59244. if (this.particleEmitterType.direction1) {
  59245. return this.particleEmitterType.direction1;
  59246. }
  59247. return BABYLON.Vector3.Zero();
  59248. },
  59249. set: function (value) {
  59250. if (this.particleEmitterType.direction1) {
  59251. this.particleEmitterType.direction1 = value;
  59252. }
  59253. },
  59254. enumerable: true,
  59255. configurable: true
  59256. });
  59257. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  59258. /**
  59259. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59260. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59261. */
  59262. get: function () {
  59263. if (this.particleEmitterType.direction2) {
  59264. return this.particleEmitterType.direction2;
  59265. }
  59266. return BABYLON.Vector3.Zero();
  59267. },
  59268. set: function (value) {
  59269. if (this.particleEmitterType.direction2) {
  59270. this.particleEmitterType.direction2 = value;
  59271. }
  59272. },
  59273. enumerable: true,
  59274. configurable: true
  59275. });
  59276. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  59277. /**
  59278. * 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.
  59279. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59280. */
  59281. get: function () {
  59282. if (this.particleEmitterType.minEmitBox) {
  59283. return this.particleEmitterType.minEmitBox;
  59284. }
  59285. return BABYLON.Vector3.Zero();
  59286. },
  59287. set: function (value) {
  59288. if (this.particleEmitterType.minEmitBox) {
  59289. this.particleEmitterType.minEmitBox = value;
  59290. }
  59291. },
  59292. enumerable: true,
  59293. configurable: true
  59294. });
  59295. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  59296. /**
  59297. * 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.
  59298. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59299. */
  59300. get: function () {
  59301. if (this.particleEmitterType.maxEmitBox) {
  59302. return this.particleEmitterType.maxEmitBox;
  59303. }
  59304. return BABYLON.Vector3.Zero();
  59305. },
  59306. set: function (value) {
  59307. if (this.particleEmitterType.maxEmitBox) {
  59308. this.particleEmitterType.maxEmitBox = value;
  59309. }
  59310. },
  59311. enumerable: true,
  59312. configurable: true
  59313. });
  59314. /**
  59315. * Gets the maximum number of particles active at the same time.
  59316. * @returns The max number of active particles.
  59317. */
  59318. GPUParticleSystem.prototype.getCapacity = function () {
  59319. return this._capacity;
  59320. };
  59321. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  59322. /**
  59323. * Gets or set the number of active particles
  59324. */
  59325. get: function () {
  59326. return this._activeCount;
  59327. },
  59328. set: function (value) {
  59329. this._activeCount = Math.min(value, this._capacity);
  59330. },
  59331. enumerable: true,
  59332. configurable: true
  59333. });
  59334. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  59335. /**
  59336. * Gets whether an animation sprite sheet is enabled or not on the particle system
  59337. */
  59338. get: function () {
  59339. return this._isAnimationSheetEnabled;
  59340. },
  59341. enumerable: true,
  59342. configurable: true
  59343. });
  59344. /**
  59345. * Is this system ready to be used/rendered
  59346. * @return true if the system is ready
  59347. */
  59348. GPUParticleSystem.prototype.isReady = function () {
  59349. if (!this._updateEffect) {
  59350. this._recreateUpdateEffect();
  59351. this._recreateRenderEffect();
  59352. return false;
  59353. }
  59354. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59355. return false;
  59356. }
  59357. return true;
  59358. };
  59359. /**
  59360. * Gets Wether the system has been started.
  59361. * @returns True if it has been started, otherwise false.
  59362. */
  59363. GPUParticleSystem.prototype.isStarted = function () {
  59364. return this._started;
  59365. };
  59366. /**
  59367. * Starts the particle system and begins to emit
  59368. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  59369. */
  59370. GPUParticleSystem.prototype.start = function (delay) {
  59371. var _this = this;
  59372. if (delay === void 0) { delay = 0; }
  59373. if (delay) {
  59374. setTimeout(function () {
  59375. _this.start(0);
  59376. }, delay);
  59377. return;
  59378. }
  59379. this._started = true;
  59380. this._stopped = false;
  59381. this._preWarmDone = false;
  59382. };
  59383. /**
  59384. * Stops the particle system.
  59385. */
  59386. GPUParticleSystem.prototype.stop = function () {
  59387. this._stopped = true;
  59388. };
  59389. /**
  59390. * Remove all active particles
  59391. */
  59392. GPUParticleSystem.prototype.reset = function () {
  59393. this._releaseBuffers();
  59394. this._releaseVAOs();
  59395. this._currentActiveCount = 0;
  59396. this._targetIndex = 0;
  59397. };
  59398. /**
  59399. * Returns the string "GPUParticleSystem"
  59400. * @returns a string containing the class name
  59401. */
  59402. GPUParticleSystem.prototype.getClassName = function () {
  59403. return "GPUParticleSystem";
  59404. };
  59405. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  59406. /**
  59407. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  59408. */
  59409. get: function () {
  59410. return this._isBillboardBased;
  59411. },
  59412. set: function (value) {
  59413. if (this._isBillboardBased === value) {
  59414. return;
  59415. }
  59416. this._isBillboardBased = value;
  59417. this._releaseBuffers();
  59418. },
  59419. enumerable: true,
  59420. configurable: true
  59421. });
  59422. /**
  59423. * Gets the current list of color gradients.
  59424. * You must use addColorGradient and removeColorGradient to udpate this list
  59425. * @returns the list of color gradients
  59426. */
  59427. GPUParticleSystem.prototype.getColorGradients = function () {
  59428. return this._colorGradients;
  59429. };
  59430. /**
  59431. * Gets the current list of size gradients.
  59432. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59433. * @returns the list of size gradients
  59434. */
  59435. GPUParticleSystem.prototype.getSizeGradients = function () {
  59436. return this._sizeGradients;
  59437. };
  59438. /**
  59439. * Gets the current list of angular speed gradients.
  59440. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59441. * @returns the list of angular speed gradients
  59442. */
  59443. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  59444. return this._angularSpeedGradients;
  59445. };
  59446. /**
  59447. * Gets the current list of velocity gradients.
  59448. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  59449. * @returns the list of angular speed gradients
  59450. */
  59451. GPUParticleSystem.prototype.getVelocityGradients = function () {
  59452. return this._velocityGradients;
  59453. };
  59454. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  59455. if (!gradients) {
  59456. return this;
  59457. }
  59458. var index = 0;
  59459. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59460. var valueGradient = gradients_1[_i];
  59461. if (valueGradient.gradient === gradient) {
  59462. gradients.splice(index, 1);
  59463. break;
  59464. }
  59465. index++;
  59466. }
  59467. if (texture) {
  59468. texture.dispose();
  59469. }
  59470. this._releaseBuffers();
  59471. return this;
  59472. };
  59473. /**
  59474. * Adds a new color gradient
  59475. * @param gradient defines the gradient to use (between 0 and 1)
  59476. * @param color defines the color to affect to the specified gradient
  59477. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59478. * @returns the current particle system
  59479. */
  59480. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59481. if (!this._colorGradients) {
  59482. this._colorGradients = [];
  59483. }
  59484. var colorGradient = new BABYLON.ColorGradient();
  59485. colorGradient.gradient = gradient;
  59486. colorGradient.color1 = color1;
  59487. this._colorGradients.push(colorGradient);
  59488. this._colorGradients.sort(function (a, b) {
  59489. if (a.gradient < b.gradient) {
  59490. return -1;
  59491. }
  59492. else if (a.gradient > b.gradient) {
  59493. return 1;
  59494. }
  59495. return 0;
  59496. });
  59497. if (this._colorGradientsTexture) {
  59498. this._colorGradientsTexture.dispose();
  59499. this._colorGradientsTexture = null;
  59500. }
  59501. this._releaseBuffers();
  59502. return this;
  59503. };
  59504. /**
  59505. * Remove a specific color gradient
  59506. * @param gradient defines the gradient to remove
  59507. * @returns the current particle system
  59508. */
  59509. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  59510. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  59511. this._colorGradientsTexture = null;
  59512. return this;
  59513. };
  59514. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  59515. var valueGradient = new BABYLON.FactorGradient();
  59516. valueGradient.gradient = gradient;
  59517. valueGradient.factor1 = factor;
  59518. factorGradients.push(valueGradient);
  59519. factorGradients.sort(function (a, b) {
  59520. if (a.gradient < b.gradient) {
  59521. return -1;
  59522. }
  59523. else if (a.gradient > b.gradient) {
  59524. return 1;
  59525. }
  59526. return 0;
  59527. });
  59528. this._releaseBuffers();
  59529. };
  59530. /**
  59531. * Adds a new size gradient
  59532. * @param gradient defines the gradient to use (between 0 and 1)
  59533. * @param factor defines the size factor to affect to the specified gradient
  59534. * @returns the current particle system
  59535. */
  59536. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  59537. if (!this._sizeGradients) {
  59538. this._sizeGradients = [];
  59539. }
  59540. this._addFactorGradient(this._sizeGradients, gradient, factor);
  59541. if (this._sizeGradientsTexture) {
  59542. this._sizeGradientsTexture.dispose();
  59543. this._sizeGradientsTexture = null;
  59544. }
  59545. this._releaseBuffers();
  59546. return this;
  59547. };
  59548. /**
  59549. * Remove a specific size gradient
  59550. * @param gradient defines the gradient to remove
  59551. * @returns the current particle system
  59552. */
  59553. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59554. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  59555. this._sizeGradientsTexture = null;
  59556. return this;
  59557. };
  59558. /**
  59559. * Adds a new angular speed gradient
  59560. * @param gradient defines the gradient to use (between 0 and 1)
  59561. * @param factor defines the size factor to affect to the specified gradient
  59562. * @returns the current particle system
  59563. */
  59564. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  59565. if (!this._angularSpeedGradients) {
  59566. this._angularSpeedGradients = [];
  59567. }
  59568. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  59569. if (this._angularSpeedGradientsTexture) {
  59570. this._angularSpeedGradientsTexture.dispose();
  59571. this._angularSpeedGradientsTexture = null;
  59572. }
  59573. this._releaseBuffers();
  59574. return this;
  59575. };
  59576. /**
  59577. * Remove a specific angular speed gradient
  59578. * @param gradient defines the gradient to remove
  59579. * @returns the current particle system
  59580. */
  59581. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59582. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  59583. this._angularSpeedGradientsTexture = null;
  59584. return this;
  59585. };
  59586. /**
  59587. * Adds a new velocity gradient
  59588. * @param gradient defines the gradient to use (between 0 and 1)
  59589. * @param factor defines the size factor to affect to the specified gradient
  59590. * @returns the current particle system
  59591. */
  59592. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  59593. if (!this._velocityGradients) {
  59594. this._velocityGradients = [];
  59595. }
  59596. this._addFactorGradient(this._velocityGradients, gradient, factor);
  59597. if (this._velocityGradientsTexture) {
  59598. this._velocityGradientsTexture.dispose();
  59599. this._velocityGradientsTexture = null;
  59600. }
  59601. this._releaseBuffers();
  59602. return this;
  59603. };
  59604. /**
  59605. * Remove a specific velocity gradient
  59606. * @param gradient defines the gradient to remove
  59607. * @returns the current particle system
  59608. */
  59609. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59610. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  59611. this._velocityGradientsTexture = null;
  59612. return this;
  59613. };
  59614. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  59615. var updateVertexBuffers = {};
  59616. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  59617. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  59618. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  59619. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  59620. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  59621. var offset = 12;
  59622. if (!this._colorGradientsTexture) {
  59623. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  59624. offset += 4;
  59625. }
  59626. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  59627. offset += 3;
  59628. if (!this._isBillboardBased) {
  59629. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  59630. offset += 3;
  59631. }
  59632. if (this._angularSpeedGradientsTexture) {
  59633. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  59634. offset += 1;
  59635. }
  59636. else {
  59637. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  59638. offset += 2;
  59639. }
  59640. if (this._isAnimationSheetEnabled) {
  59641. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  59642. offset += 1;
  59643. }
  59644. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  59645. this._engine.bindArrayBuffer(null);
  59646. return vao;
  59647. };
  59648. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  59649. var renderVertexBuffers = {};
  59650. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  59651. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  59652. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  59653. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  59654. var offset = 12;
  59655. if (!this._colorGradientsTexture) {
  59656. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  59657. offset += 4;
  59658. }
  59659. offset += 3; // Direction
  59660. if (!this._isBillboardBased) {
  59661. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  59662. offset += 3;
  59663. }
  59664. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  59665. if (this._angularSpeedGradientsTexture) {
  59666. offset++;
  59667. }
  59668. else {
  59669. offset += 2;
  59670. }
  59671. if (this._isAnimationSheetEnabled) {
  59672. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  59673. offset += 1;
  59674. }
  59675. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  59676. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  59677. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  59678. this._engine.bindArrayBuffer(null);
  59679. return vao;
  59680. };
  59681. GPUParticleSystem.prototype._initialize = function (force) {
  59682. if (force === void 0) { force = false; }
  59683. if (this._buffer0 && !force) {
  59684. return;
  59685. }
  59686. var engine = this._scene.getEngine();
  59687. var data = new Array();
  59688. if (!this.isBillboardBased) {
  59689. this._attributesStrideSize += 3;
  59690. }
  59691. if (this._colorGradientsTexture) {
  59692. this._attributesStrideSize -= 4;
  59693. }
  59694. if (this._angularSpeedGradientsTexture) {
  59695. this._attributesStrideSize -= 1;
  59696. }
  59697. if (this._isAnimationSheetEnabled) {
  59698. this._attributesStrideSize += 1;
  59699. }
  59700. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  59701. // position
  59702. data.push(0.0);
  59703. data.push(0.0);
  59704. data.push(0.0);
  59705. // Age and life
  59706. data.push(0.0); // create the particle as a dead one to create a new one at start
  59707. data.push(0.0);
  59708. // Seed
  59709. data.push(Math.random());
  59710. data.push(Math.random());
  59711. data.push(Math.random());
  59712. data.push(Math.random());
  59713. // Size
  59714. data.push(0.0);
  59715. data.push(0.0);
  59716. data.push(0.0);
  59717. if (!this._colorGradientsTexture) {
  59718. // color
  59719. data.push(0.0);
  59720. data.push(0.0);
  59721. data.push(0.0);
  59722. data.push(0.0);
  59723. }
  59724. // direction
  59725. data.push(0.0);
  59726. data.push(0.0);
  59727. data.push(0.0);
  59728. if (!this.isBillboardBased) {
  59729. // initialDirection
  59730. data.push(0.0);
  59731. data.push(0.0);
  59732. data.push(0.0);
  59733. }
  59734. // angle
  59735. data.push(0.0);
  59736. if (!this._angularSpeedGradientsTexture) {
  59737. data.push(0.0);
  59738. }
  59739. if (this._isAnimationSheetEnabled) {
  59740. data.push(0.0);
  59741. }
  59742. }
  59743. // Sprite data
  59744. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  59745. -0.5, 0.5, 0, 1,
  59746. -0.5, -0.5, 0, 0,
  59747. 0.5, -0.5, 1, 0]);
  59748. // Buffers
  59749. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  59750. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  59751. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  59752. // Update VAO
  59753. this._updateVAO = [];
  59754. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  59755. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  59756. // Render VAO
  59757. this._renderVAO = [];
  59758. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  59759. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  59760. // Links
  59761. this._sourceBuffer = this._buffer0;
  59762. this._targetBuffer = this._buffer1;
  59763. };
  59764. /** @hidden */
  59765. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  59766. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  59767. if (this._isBillboardBased) {
  59768. defines += "\n#define BILLBOARD";
  59769. }
  59770. if (this._colorGradientsTexture) {
  59771. defines += "\n#define COLORGRADIENTS";
  59772. }
  59773. if (this._sizeGradientsTexture) {
  59774. defines += "\n#define SIZEGRADIENTS";
  59775. }
  59776. if (this._angularSpeedGradientsTexture) {
  59777. defines += "\n#define ANGULARSPEEDGRADIENTS";
  59778. }
  59779. if (this._velocityGradientsTexture) {
  59780. defines += "\n#define VELOCITYGRADIENTS";
  59781. }
  59782. if (this.isAnimationSheetEnabled) {
  59783. defines += "\n#define ANIMATESHEET";
  59784. }
  59785. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  59786. return;
  59787. }
  59788. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  59789. if (!this._colorGradientsTexture) {
  59790. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  59791. }
  59792. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  59793. if (!this._isBillboardBased) {
  59794. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  59795. }
  59796. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  59797. if (this.isAnimationSheetEnabled) {
  59798. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  59799. }
  59800. this._updateEffectOptions.defines = defines;
  59801. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  59802. };
  59803. /** @hidden */
  59804. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  59805. var defines = "";
  59806. if (this._scene.clipPlane) {
  59807. defines = "\n#define CLIPPLANE";
  59808. }
  59809. if (this._isBillboardBased) {
  59810. defines += "\n#define BILLBOARD";
  59811. switch (this.billboardMode) {
  59812. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  59813. defines += "\n#define BILLBOARDY";
  59814. break;
  59815. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  59816. default:
  59817. break;
  59818. }
  59819. }
  59820. if (this._colorGradientsTexture) {
  59821. defines += "\n#define COLORGRADIENTS";
  59822. }
  59823. if (this.isAnimationSheetEnabled) {
  59824. defines += "\n#define ANIMATESHEET";
  59825. }
  59826. if (this._renderEffect && this._renderEffect.defines === defines) {
  59827. return;
  59828. }
  59829. 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);
  59830. };
  59831. /**
  59832. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59833. * @param preWarm defines if we are in the pre-warmimg phase
  59834. */
  59835. GPUParticleSystem.prototype.animate = function (preWarm) {
  59836. if (preWarm === void 0) { preWarm = false; }
  59837. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59838. this._actualFrame += this._timeDelta;
  59839. if (!this._stopped) {
  59840. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  59841. this.stop();
  59842. }
  59843. }
  59844. };
  59845. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  59846. var texture = this[textureName];
  59847. if (!factorGradients || !factorGradients.length || texture) {
  59848. return;
  59849. }
  59850. var data = new Float32Array(this._rawTextureWidth);
  59851. for (var x = 0; x < this._rawTextureWidth; x++) {
  59852. var ratio = x / this._rawTextureWidth;
  59853. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  59854. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59855. });
  59856. }
  59857. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59858. };
  59859. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  59860. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  59861. };
  59862. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  59863. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  59864. };
  59865. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  59866. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  59867. };
  59868. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  59869. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  59870. return;
  59871. }
  59872. var data = new Uint8Array(this._rawTextureWidth * 4);
  59873. var tmpColor = BABYLON.Tmp.Color4[0];
  59874. for (var x = 0; x < this._rawTextureWidth; x++) {
  59875. var ratio = x / this._rawTextureWidth;
  59876. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  59877. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  59878. data[x * 4] = tmpColor.r * 255;
  59879. data[x * 4 + 1] = tmpColor.g * 255;
  59880. data[x * 4 + 2] = tmpColor.b * 255;
  59881. data[x * 4 + 3] = tmpColor.a * 255;
  59882. });
  59883. }
  59884. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59885. };
  59886. /**
  59887. * Renders the particle system in its current state
  59888. * @param preWarm defines if the system should only update the particles but not render them
  59889. * @returns the current number of particles
  59890. */
  59891. GPUParticleSystem.prototype.render = function (preWarm) {
  59892. if (preWarm === void 0) { preWarm = false; }
  59893. if (!this._started) {
  59894. return 0;
  59895. }
  59896. this._createColorGradientTexture();
  59897. this._createSizeGradientTexture();
  59898. this._createAngularSpeedGradientTexture();
  59899. this._createVelocityGradientTexture();
  59900. this._recreateUpdateEffect();
  59901. this._recreateRenderEffect();
  59902. if (!this.isReady()) {
  59903. return 0;
  59904. }
  59905. if (!preWarm) {
  59906. if (!this._preWarmDone && this.preWarmCycles) {
  59907. for (var index = 0; index < this.preWarmCycles; index++) {
  59908. this.animate(true);
  59909. this.render(true);
  59910. }
  59911. this._preWarmDone = true;
  59912. }
  59913. if (this._currentRenderId === this._scene.getRenderId()) {
  59914. return 0;
  59915. }
  59916. this._currentRenderId = this._scene.getRenderId();
  59917. }
  59918. // Get everything ready to render
  59919. this._initialize();
  59920. this._accumulatedCount += this.emitRate * this._timeDelta;
  59921. if (this._accumulatedCount > 1) {
  59922. var intPart = this._accumulatedCount | 0;
  59923. this._accumulatedCount -= intPart;
  59924. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  59925. }
  59926. if (!this._currentActiveCount) {
  59927. return 0;
  59928. }
  59929. // Enable update effect
  59930. this._engine.enableEffect(this._updateEffect);
  59931. this._engine.setState(false);
  59932. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  59933. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  59934. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  59935. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  59936. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  59937. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  59938. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  59939. if (!this._colorGradientsTexture) {
  59940. this._updateEffect.setDirectColor4("color1", this.color1);
  59941. this._updateEffect.setDirectColor4("color2", this.color2);
  59942. }
  59943. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  59944. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  59945. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  59946. this._updateEffect.setVector3("gravity", this.gravity);
  59947. if (this._sizeGradientsTexture) {
  59948. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  59949. }
  59950. if (this._angularSpeedGradientsTexture) {
  59951. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  59952. }
  59953. if (this._velocityGradientsTexture) {
  59954. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  59955. }
  59956. if (this.particleEmitterType) {
  59957. this.particleEmitterType.applyToShader(this._updateEffect);
  59958. }
  59959. if (this._isAnimationSheetEnabled) {
  59960. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  59961. }
  59962. var emitterWM;
  59963. if (this.emitter.position) {
  59964. var emitterMesh = this.emitter;
  59965. emitterWM = emitterMesh.getWorldMatrix();
  59966. }
  59967. else {
  59968. var emitterPosition = this.emitter;
  59969. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59970. }
  59971. this._updateEffect.setMatrix("emitterWM", emitterWM);
  59972. // Bind source VAO
  59973. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  59974. // Update
  59975. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  59976. this._engine.setRasterizerState(false);
  59977. this._engine.beginTransformFeedback(true);
  59978. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  59979. this._engine.endTransformFeedback();
  59980. this._engine.setRasterizerState(true);
  59981. this._engine.bindTransformFeedbackBuffer(null);
  59982. if (!preWarm) {
  59983. // Enable render effect
  59984. this._engine.enableEffect(this._renderEffect);
  59985. var viewMatrix = this._scene.getViewMatrix();
  59986. this._renderEffect.setMatrix("view", viewMatrix);
  59987. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  59988. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  59989. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  59990. if (this._colorGradientsTexture) {
  59991. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  59992. }
  59993. else {
  59994. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  59995. }
  59996. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59997. var baseSize = this.particleTexture.getBaseSize();
  59998. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59999. }
  60000. if (this._isBillboardBased) {
  60001. var camera = this._scene.activeCamera;
  60002. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60003. }
  60004. if (this._scene.clipPlane) {
  60005. var clipPlane = this._scene.clipPlane;
  60006. var invView = viewMatrix.clone();
  60007. invView.invert();
  60008. this._renderEffect.setMatrix("invView", invView);
  60009. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60010. }
  60011. // Draw order
  60012. switch (this.blendMode) {
  60013. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60014. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60015. break;
  60016. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60017. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60018. break;
  60019. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60020. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60021. break;
  60022. }
  60023. if (this.forceDepthWrite) {
  60024. this._engine.setDepthWrite(true);
  60025. }
  60026. // Bind source VAO
  60027. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60028. // Render
  60029. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60030. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60031. }
  60032. // Switch VAOs
  60033. this._targetIndex++;
  60034. if (this._targetIndex === 2) {
  60035. this._targetIndex = 0;
  60036. }
  60037. // Switch buffers
  60038. var tmpBuffer = this._sourceBuffer;
  60039. this._sourceBuffer = this._targetBuffer;
  60040. this._targetBuffer = tmpBuffer;
  60041. return this._currentActiveCount;
  60042. };
  60043. /**
  60044. * Rebuilds the particle system
  60045. */
  60046. GPUParticleSystem.prototype.rebuild = function () {
  60047. this._initialize(true);
  60048. };
  60049. GPUParticleSystem.prototype._releaseBuffers = function () {
  60050. if (this._buffer0) {
  60051. this._buffer0.dispose();
  60052. this._buffer0 = null;
  60053. }
  60054. if (this._buffer1) {
  60055. this._buffer1.dispose();
  60056. this._buffer1 = null;
  60057. }
  60058. if (this._spriteBuffer) {
  60059. this._spriteBuffer.dispose();
  60060. this._spriteBuffer = null;
  60061. }
  60062. };
  60063. GPUParticleSystem.prototype._releaseVAOs = function () {
  60064. if (!this._updateVAO) {
  60065. return;
  60066. }
  60067. for (var index = 0; index < this._updateVAO.length; index++) {
  60068. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60069. }
  60070. this._updateVAO = [];
  60071. for (var index = 0; index < this._renderVAO.length; index++) {
  60072. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60073. }
  60074. this._renderVAO = [];
  60075. };
  60076. /**
  60077. * Disposes the particle system and free the associated resources
  60078. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60079. */
  60080. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60081. if (disposeTexture === void 0) { disposeTexture = true; }
  60082. var index = this._scene.particleSystems.indexOf(this);
  60083. if (index > -1) {
  60084. this._scene.particleSystems.splice(index, 1);
  60085. }
  60086. this._releaseBuffers();
  60087. this._releaseVAOs();
  60088. if (this._colorGradientsTexture) {
  60089. this._colorGradientsTexture.dispose();
  60090. this._colorGradientsTexture = null;
  60091. }
  60092. if (this._sizeGradientsTexture) {
  60093. this._sizeGradientsTexture.dispose();
  60094. this._sizeGradientsTexture = null;
  60095. }
  60096. if (this._angularSpeedGradientsTexture) {
  60097. this._angularSpeedGradientsTexture.dispose();
  60098. this._angularSpeedGradientsTexture = null;
  60099. }
  60100. if (this._velocityGradientsTexture) {
  60101. this._velocityGradientsTexture.dispose();
  60102. this._velocityGradientsTexture = null;
  60103. }
  60104. if (this._randomTexture) {
  60105. this._randomTexture.dispose();
  60106. this._randomTexture = null;
  60107. }
  60108. if (this._randomTexture2) {
  60109. this._randomTexture2.dispose();
  60110. this._randomTexture2 = null;
  60111. }
  60112. if (disposeTexture && this.particleTexture) {
  60113. this.particleTexture.dispose();
  60114. this.particleTexture = null;
  60115. }
  60116. // Callback
  60117. this.onDisposeObservable.notifyObservers(this);
  60118. this.onDisposeObservable.clear();
  60119. };
  60120. /**
  60121. * Clones the particle system.
  60122. * @param name The name of the cloned object
  60123. * @param newEmitter The new emitter to use
  60124. * @returns the cloned particle system
  60125. */
  60126. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60127. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60128. BABYLON.Tools.DeepCopy(this, result);
  60129. if (newEmitter === undefined) {
  60130. newEmitter = this.emitter;
  60131. }
  60132. result.emitter = newEmitter;
  60133. if (this.particleTexture) {
  60134. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60135. }
  60136. return result;
  60137. };
  60138. /**
  60139. * Serializes the particle system to a JSON object.
  60140. * @returns the JSON object
  60141. */
  60142. GPUParticleSystem.prototype.serialize = function () {
  60143. var serializationObject = {};
  60144. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60145. serializationObject.activeParticleCount = this.activeParticleCount;
  60146. return serializationObject;
  60147. };
  60148. /**
  60149. * Parses a JSON object to create a GPU particle system.
  60150. * @param parsedParticleSystem The JSON object to parse
  60151. * @param scene The scene to create the particle system in
  60152. * @param rootUrl The root url to use to load external dependencies like texture
  60153. * @returns the parsed GPU particle system
  60154. */
  60155. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60156. var name = parsedParticleSystem.name;
  60157. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60158. if (parsedParticleSystem.activeParticleCount) {
  60159. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60160. }
  60161. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60162. return particleSystem;
  60163. };
  60164. return GPUParticleSystem;
  60165. }());
  60166. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60167. })(BABYLON || (BABYLON = {}));
  60168. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60169. var BABYLON;
  60170. (function (BABYLON) {
  60171. /**
  60172. * Represents one particle of a solid particle system.
  60173. */
  60174. var SolidParticle = /** @class */ (function () {
  60175. /**
  60176. * Creates a Solid Particle object.
  60177. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60178. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60179. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60180. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60181. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60182. * @param shapeId (integer) is the model shape identifier in the SPS.
  60183. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60184. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60185. */
  60186. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60187. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60188. /**
  60189. * particle global index
  60190. */
  60191. this.idx = 0;
  60192. /**
  60193. * The color of the particle
  60194. */
  60195. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60196. /**
  60197. * The world space position of the particle.
  60198. */
  60199. this.position = BABYLON.Vector3.Zero();
  60200. /**
  60201. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60202. */
  60203. this.rotation = BABYLON.Vector3.Zero();
  60204. /**
  60205. * The scaling of the particle.
  60206. */
  60207. this.scaling = BABYLON.Vector3.One();
  60208. /**
  60209. * The uvs of the particle.
  60210. */
  60211. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60212. /**
  60213. * The current speed of the particle.
  60214. */
  60215. this.velocity = BABYLON.Vector3.Zero();
  60216. /**
  60217. * The pivot point in the particle local space.
  60218. */
  60219. this.pivot = BABYLON.Vector3.Zero();
  60220. /**
  60221. * Must the particle be translated from its pivot point in its local space ?
  60222. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60223. * Default : false
  60224. */
  60225. this.translateFromPivot = false;
  60226. /**
  60227. * Is the particle active or not ?
  60228. */
  60229. this.alive = true;
  60230. /**
  60231. * Is the particle visible or not ?
  60232. */
  60233. this.isVisible = true;
  60234. /**
  60235. * Index of this particle in the global "positions" array (Internal use)
  60236. */
  60237. this._pos = 0;
  60238. /**
  60239. * Index of this particle in the global "indices" array (Internal use)
  60240. */
  60241. this._ind = 0;
  60242. /**
  60243. * ModelShape id of this particle
  60244. */
  60245. this.shapeId = 0;
  60246. /**
  60247. * Index of the particle in its shape id (Internal use)
  60248. */
  60249. this.idxInShape = 0;
  60250. /**
  60251. * Still set as invisible in order to skip useless computations (Internal use)
  60252. */
  60253. this._stillInvisible = false;
  60254. /**
  60255. * Last computed particle rotation matrix
  60256. */
  60257. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60258. /**
  60259. * Parent particle Id, if any.
  60260. * Default null.
  60261. */
  60262. this.parentId = null;
  60263. /**
  60264. * Internal global position in the SPS.
  60265. */
  60266. this._globalPosition = BABYLON.Vector3.Zero();
  60267. this.idx = particleIndex;
  60268. this._pos = positionIndex;
  60269. this._ind = indiceIndex;
  60270. this._model = model;
  60271. this.shapeId = shapeId;
  60272. this.idxInShape = idxInShape;
  60273. this._sps = sps;
  60274. if (modelBoundingInfo) {
  60275. this._modelBoundingInfo = modelBoundingInfo;
  60276. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60277. }
  60278. }
  60279. Object.defineProperty(SolidParticle.prototype, "scale", {
  60280. /**
  60281. * Legacy support, changed scale to scaling
  60282. */
  60283. get: function () {
  60284. return this.scaling;
  60285. },
  60286. /**
  60287. * Legacy support, changed scale to scaling
  60288. */
  60289. set: function (scale) {
  60290. this.scaling = scale;
  60291. },
  60292. enumerable: true,
  60293. configurable: true
  60294. });
  60295. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  60296. /**
  60297. * Legacy support, changed quaternion to rotationQuaternion
  60298. */
  60299. get: function () {
  60300. return this.rotationQuaternion;
  60301. },
  60302. /**
  60303. * Legacy support, changed quaternion to rotationQuaternion
  60304. */
  60305. set: function (q) {
  60306. this.rotationQuaternion = q;
  60307. },
  60308. enumerable: true,
  60309. configurable: true
  60310. });
  60311. /**
  60312. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  60313. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  60314. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  60315. * @returns true if it intersects
  60316. */
  60317. SolidParticle.prototype.intersectsMesh = function (target) {
  60318. if (!this._boundingInfo || !target._boundingInfo) {
  60319. return false;
  60320. }
  60321. if (this._sps._bSphereOnly) {
  60322. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  60323. }
  60324. return this._boundingInfo.intersects(target._boundingInfo, false);
  60325. };
  60326. return SolidParticle;
  60327. }());
  60328. BABYLON.SolidParticle = SolidParticle;
  60329. /**
  60330. * Represents the shape of the model used by one particle of a solid particle system.
  60331. * SPS internal tool, don't use it manually.
  60332. */
  60333. var ModelShape = /** @class */ (function () {
  60334. /**
  60335. * 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.
  60336. * SPS internal tool, don't use it manually.
  60337. * @hidden
  60338. */
  60339. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  60340. /**
  60341. * length of the shape in the model indices array (internal use)
  60342. */
  60343. this._indicesLength = 0;
  60344. this.shapeID = id;
  60345. this._shape = shape;
  60346. this._indicesLength = indicesLength;
  60347. this._shapeUV = shapeUV;
  60348. this._positionFunction = posFunction;
  60349. this._vertexFunction = vtxFunction;
  60350. }
  60351. return ModelShape;
  60352. }());
  60353. BABYLON.ModelShape = ModelShape;
  60354. /**
  60355. * Represents a Depth Sorted Particle in the solid particle system.
  60356. */
  60357. var DepthSortedParticle = /** @class */ (function () {
  60358. function DepthSortedParticle() {
  60359. /**
  60360. * Index of the particle in the "indices" array
  60361. */
  60362. this.ind = 0;
  60363. /**
  60364. * Length of the particle shape in the "indices" array
  60365. */
  60366. this.indicesLength = 0;
  60367. /**
  60368. * Squared distance from the particle to the camera
  60369. */
  60370. this.sqDistance = 0.0;
  60371. }
  60372. return DepthSortedParticle;
  60373. }());
  60374. BABYLON.DepthSortedParticle = DepthSortedParticle;
  60375. })(BABYLON || (BABYLON = {}));
  60376. //# sourceMappingURL=babylon.solidParticle.js.map
  60377. var BABYLON;
  60378. (function (BABYLON) {
  60379. /**
  60380. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  60381. *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.
  60382. * The SPS is also a particle system. It provides some methods to manage the particles.
  60383. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  60384. *
  60385. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  60386. */
  60387. var SolidParticleSystem = /** @class */ (function () {
  60388. /**
  60389. * Creates a SPS (Solid Particle System) object.
  60390. * @param name (String) is the SPS name, this will be the underlying mesh name.
  60391. * @param scene (Scene) is the scene in which the SPS is added.
  60392. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  60393. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  60394. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  60395. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  60396. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  60397. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  60398. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  60399. */
  60400. function SolidParticleSystem(name, scene, options) {
  60401. /**
  60402. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  60403. * Example : var p = SPS.particles[i];
  60404. */
  60405. this.particles = new Array();
  60406. /**
  60407. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  60408. */
  60409. this.nbParticles = 0;
  60410. /**
  60411. * If the particles must ever face the camera (default false). Useful for planar particles.
  60412. */
  60413. this.billboard = false;
  60414. /**
  60415. * Recompute normals when adding a shape
  60416. */
  60417. this.recomputeNormals = true;
  60418. /**
  60419. * This a counter ofr your own usage. It's not set by any SPS functions.
  60420. */
  60421. this.counter = 0;
  60422. /**
  60423. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60424. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  60425. */
  60426. this.vars = {};
  60427. /**
  60428. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  60429. */
  60430. this._bSphereOnly = false;
  60431. /**
  60432. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  60433. */
  60434. this._bSphereRadiusFactor = 1.0;
  60435. this._positions = new Array();
  60436. this._indices = new Array();
  60437. this._normals = new Array();
  60438. this._colors = new Array();
  60439. this._uvs = new Array();
  60440. this._index = 0; // indices index
  60441. this._updatable = true;
  60442. this._pickable = false;
  60443. this._isVisibilityBoxLocked = false;
  60444. this._alwaysVisible = false;
  60445. this._depthSort = false;
  60446. this._shapeCounter = 0;
  60447. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  60448. this._color = new BABYLON.Color4(0, 0, 0, 0);
  60449. this._computeParticleColor = true;
  60450. this._computeParticleTexture = true;
  60451. this._computeParticleRotation = true;
  60452. this._computeParticleVertex = false;
  60453. this._computeBoundingBox = false;
  60454. this._depthSortParticles = true;
  60455. this._cam_axisZ = BABYLON.Vector3.Zero();
  60456. this._cam_axisY = BABYLON.Vector3.Zero();
  60457. this._cam_axisX = BABYLON.Vector3.Zero();
  60458. this._axisZ = BABYLON.Axis.Z;
  60459. this._camDir = BABYLON.Vector3.Zero();
  60460. this._camInvertedPosition = BABYLON.Vector3.Zero();
  60461. this._rotMatrix = new BABYLON.Matrix();
  60462. this._invertMatrix = new BABYLON.Matrix();
  60463. this._rotated = BABYLON.Vector3.Zero();
  60464. this._quaternion = new BABYLON.Quaternion();
  60465. this._vertex = BABYLON.Vector3.Zero();
  60466. this._normal = BABYLON.Vector3.Zero();
  60467. this._yaw = 0.0;
  60468. this._pitch = 0.0;
  60469. this._roll = 0.0;
  60470. this._halfroll = 0.0;
  60471. this._halfpitch = 0.0;
  60472. this._halfyaw = 0.0;
  60473. this._sinRoll = 0.0;
  60474. this._cosRoll = 0.0;
  60475. this._sinPitch = 0.0;
  60476. this._cosPitch = 0.0;
  60477. this._sinYaw = 0.0;
  60478. this._cosYaw = 0.0;
  60479. this._mustUnrotateFixedNormals = false;
  60480. this._minimum = BABYLON.Vector3.Zero();
  60481. this._maximum = BABYLON.Vector3.Zero();
  60482. this._minBbox = BABYLON.Vector3.Zero();
  60483. this._maxBbox = BABYLON.Vector3.Zero();
  60484. this._particlesIntersect = false;
  60485. this._depthSortFunction = function (p1, p2) {
  60486. return (p2.sqDistance - p1.sqDistance);
  60487. };
  60488. this._needs32Bits = false;
  60489. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  60490. this._scaledPivot = BABYLON.Vector3.Zero();
  60491. this._particleHasParent = false;
  60492. this.name = name;
  60493. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60494. this._camera = scene.activeCamera;
  60495. this._pickable = options ? options.isPickable : false;
  60496. this._depthSort = options ? options.enableDepthSort : false;
  60497. this._particlesIntersect = options ? options.particleIntersection : false;
  60498. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  60499. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  60500. if (options && options.updatable !== undefined) {
  60501. this._updatable = options.updatable;
  60502. }
  60503. else {
  60504. this._updatable = true;
  60505. }
  60506. if (this._pickable) {
  60507. this.pickedParticles = [];
  60508. }
  60509. if (this._depthSort) {
  60510. this.depthSortedParticles = [];
  60511. }
  60512. }
  60513. /**
  60514. * Builds the SPS underlying mesh. Returns a standard Mesh.
  60515. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  60516. * @returns the created mesh
  60517. */
  60518. SolidParticleSystem.prototype.buildMesh = function () {
  60519. if (this.nbParticles === 0) {
  60520. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  60521. this.addShape(triangle, 1);
  60522. triangle.dispose();
  60523. }
  60524. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  60525. this._positions32 = new Float32Array(this._positions);
  60526. this._uvs32 = new Float32Array(this._uvs);
  60527. this._colors32 = new Float32Array(this._colors);
  60528. if (this.recomputeNormals) {
  60529. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  60530. }
  60531. this._normals32 = new Float32Array(this._normals);
  60532. this._fixedNormal32 = new Float32Array(this._normals);
  60533. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  60534. this._unrotateFixedNormals();
  60535. }
  60536. var vertexData = new BABYLON.VertexData();
  60537. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  60538. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  60539. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  60540. if (this._uvs32.length > 0) {
  60541. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  60542. }
  60543. if (this._colors32.length > 0) {
  60544. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  60545. }
  60546. var mesh = new BABYLON.Mesh(this.name, this._scene);
  60547. vertexData.applyToMesh(mesh, this._updatable);
  60548. this.mesh = mesh;
  60549. this.mesh.isPickable = this._pickable;
  60550. // free memory
  60551. if (!this._depthSort) {
  60552. this._indices = null;
  60553. }
  60554. this._positions = null;
  60555. this._normals = null;
  60556. this._uvs = null;
  60557. this._colors = null;
  60558. if (!this._updatable) {
  60559. this.particles.length = 0;
  60560. }
  60561. return mesh;
  60562. };
  60563. /**
  60564. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  60565. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  60566. * Thus the particles generated from `digest()` have their property `position` set yet.
  60567. * @param mesh ( Mesh ) is the mesh to be digested
  60568. * @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
  60569. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  60570. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  60571. * @returns the current SPS
  60572. */
  60573. SolidParticleSystem.prototype.digest = function (mesh, options) {
  60574. var size = (options && options.facetNb) || 1;
  60575. var number = (options && options.number) || 0;
  60576. var delta = (options && options.delta) || 0;
  60577. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60578. var meshInd = mesh.getIndices();
  60579. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60580. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60581. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60582. var f = 0; // facet counter
  60583. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  60584. // compute size from number
  60585. if (number) {
  60586. number = (number > totalFacets) ? totalFacets : number;
  60587. size = Math.round(totalFacets / number);
  60588. delta = 0;
  60589. }
  60590. else {
  60591. size = (size > totalFacets) ? totalFacets : size;
  60592. }
  60593. var facetPos = []; // submesh positions
  60594. var facetInd = []; // submesh indices
  60595. var facetUV = []; // submesh UV
  60596. var facetCol = []; // submesh colors
  60597. var barycenter = BABYLON.Vector3.Zero();
  60598. var sizeO = size;
  60599. while (f < totalFacets) {
  60600. size = sizeO + Math.floor((1 + delta) * Math.random());
  60601. if (f > totalFacets - size) {
  60602. size = totalFacets - f;
  60603. }
  60604. // reset temp arrays
  60605. facetPos.length = 0;
  60606. facetInd.length = 0;
  60607. facetUV.length = 0;
  60608. facetCol.length = 0;
  60609. // iterate over "size" facets
  60610. var fi = 0;
  60611. for (var j = f * 3; j < (f + size) * 3; j++) {
  60612. facetInd.push(fi);
  60613. var i = meshInd[j];
  60614. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  60615. if (meshUV) {
  60616. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  60617. }
  60618. if (meshCol) {
  60619. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  60620. }
  60621. fi++;
  60622. }
  60623. // create a model shape for each single particle
  60624. var idx = this.nbParticles;
  60625. var shape = this._posToShape(facetPos);
  60626. var shapeUV = this._uvsToShapeUV(facetUV);
  60627. // compute the barycenter of the shape
  60628. var v;
  60629. for (v = 0; v < shape.length; v++) {
  60630. barycenter.addInPlace(shape[v]);
  60631. }
  60632. barycenter.scaleInPlace(1 / shape.length);
  60633. // shift the shape from its barycenter to the origin
  60634. for (v = 0; v < shape.length; v++) {
  60635. shape[v].subtractInPlace(barycenter);
  60636. }
  60637. var bInfo;
  60638. if (this._particlesIntersect) {
  60639. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  60640. }
  60641. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  60642. // add the particle in the SPS
  60643. var currentPos = this._positions.length;
  60644. var currentInd = this._indices.length;
  60645. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  60646. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  60647. // initialize the particle position
  60648. this.particles[this.nbParticles].position.addInPlace(barycenter);
  60649. this._index += shape.length;
  60650. idx++;
  60651. this.nbParticles++;
  60652. this._shapeCounter++;
  60653. f += size;
  60654. }
  60655. return this;
  60656. };
  60657. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  60658. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  60659. var index = 0;
  60660. var idx = 0;
  60661. for (var p = 0; p < this.particles.length; p++) {
  60662. this._particle = this.particles[p];
  60663. this._shape = this._particle._model._shape;
  60664. if (this._particle.rotationQuaternion) {
  60665. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  60666. }
  60667. else {
  60668. this._yaw = this._particle.rotation.y;
  60669. this._pitch = this._particle.rotation.x;
  60670. this._roll = this._particle.rotation.z;
  60671. this._quaternionRotationYPR();
  60672. }
  60673. this._quaternionToRotationMatrix();
  60674. this._rotMatrix.invertToRef(this._invertMatrix);
  60675. for (var pt = 0; pt < this._shape.length; pt++) {
  60676. idx = index + pt * 3;
  60677. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  60678. this._fixedNormal32[idx] = this._normal.x;
  60679. this._fixedNormal32[idx + 1] = this._normal.y;
  60680. this._fixedNormal32[idx + 2] = this._normal.z;
  60681. }
  60682. index = idx + 3;
  60683. }
  60684. };
  60685. //reset copy
  60686. SolidParticleSystem.prototype._resetCopy = function () {
  60687. this._copy.position.x = 0;
  60688. this._copy.position.y = 0;
  60689. this._copy.position.z = 0;
  60690. this._copy.rotation.x = 0;
  60691. this._copy.rotation.y = 0;
  60692. this._copy.rotation.z = 0;
  60693. this._copy.rotationQuaternion = null;
  60694. this._copy.scaling.x = 1.0;
  60695. this._copy.scaling.y = 1.0;
  60696. this._copy.scaling.z = 1.0;
  60697. this._copy.uvs.x = 0;
  60698. this._copy.uvs.y = 0;
  60699. this._copy.uvs.z = 1.0;
  60700. this._copy.uvs.w = 1.0;
  60701. this._copy.color = null;
  60702. this._copy.translateFromPivot = false;
  60703. };
  60704. // _meshBuilder : inserts the shape model in the global SPS mesh
  60705. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  60706. var i;
  60707. var u = 0;
  60708. var c = 0;
  60709. var n = 0;
  60710. this._resetCopy();
  60711. if (options && options.positionFunction) { // call to custom positionFunction
  60712. options.positionFunction(this._copy, idx, idxInShape);
  60713. this._mustUnrotateFixedNormals = true;
  60714. }
  60715. if (this._copy.rotationQuaternion) {
  60716. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  60717. }
  60718. else {
  60719. this._yaw = this._copy.rotation.y;
  60720. this._pitch = this._copy.rotation.x;
  60721. this._roll = this._copy.rotation.z;
  60722. this._quaternionRotationYPR();
  60723. }
  60724. this._quaternionToRotationMatrix();
  60725. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  60726. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  60727. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  60728. if (this._copy.translateFromPivot) {
  60729. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  60730. }
  60731. else {
  60732. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  60733. }
  60734. for (i = 0; i < shape.length; i++) {
  60735. this._vertex.x = shape[i].x;
  60736. this._vertex.y = shape[i].y;
  60737. this._vertex.z = shape[i].z;
  60738. if (options && options.vertexFunction) {
  60739. options.vertexFunction(this._copy, this._vertex, i);
  60740. }
  60741. this._vertex.x *= this._copy.scaling.x;
  60742. this._vertex.y *= this._copy.scaling.y;
  60743. this._vertex.z *= this._copy.scaling.z;
  60744. this._vertex.x -= this._scaledPivot.x;
  60745. this._vertex.y -= this._scaledPivot.y;
  60746. this._vertex.z -= this._scaledPivot.z;
  60747. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  60748. this._rotated.addInPlace(this._pivotBackTranslation);
  60749. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  60750. if (meshUV) {
  60751. 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);
  60752. u += 2;
  60753. }
  60754. if (this._copy.color) {
  60755. this._color = this._copy.color;
  60756. }
  60757. else if (meshCol && meshCol[c] !== undefined) {
  60758. this._color.r = meshCol[c];
  60759. this._color.g = meshCol[c + 1];
  60760. this._color.b = meshCol[c + 2];
  60761. this._color.a = meshCol[c + 3];
  60762. }
  60763. else {
  60764. this._color.r = 1.0;
  60765. this._color.g = 1.0;
  60766. this._color.b = 1.0;
  60767. this._color.a = 1.0;
  60768. }
  60769. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  60770. c += 4;
  60771. if (!this.recomputeNormals && meshNor) {
  60772. this._normal.x = meshNor[n];
  60773. this._normal.y = meshNor[n + 1];
  60774. this._normal.z = meshNor[n + 2];
  60775. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  60776. normals.push(this._normal.x, this._normal.y, this._normal.z);
  60777. n += 3;
  60778. }
  60779. }
  60780. for (i = 0; i < meshInd.length; i++) {
  60781. var current_ind = p + meshInd[i];
  60782. indices.push(current_ind);
  60783. if (current_ind > 65535) {
  60784. this._needs32Bits = true;
  60785. }
  60786. }
  60787. if (this._pickable) {
  60788. var nbfaces = meshInd.length / 3;
  60789. for (i = 0; i < nbfaces; i++) {
  60790. this.pickedParticles.push({ idx: idx, faceId: i });
  60791. }
  60792. }
  60793. if (this._depthSort) {
  60794. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  60795. }
  60796. return this._copy;
  60797. };
  60798. // returns a shape array from positions array
  60799. SolidParticleSystem.prototype._posToShape = function (positions) {
  60800. var shape = [];
  60801. for (var i = 0; i < positions.length; i += 3) {
  60802. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  60803. }
  60804. return shape;
  60805. };
  60806. // returns a shapeUV array from a Vector4 uvs
  60807. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  60808. var shapeUV = [];
  60809. if (uvs) {
  60810. for (var i = 0; i < uvs.length; i++)
  60811. shapeUV.push(uvs[i]);
  60812. }
  60813. return shapeUV;
  60814. };
  60815. // adds a new particle object in the particles array
  60816. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  60817. if (bInfo === void 0) { bInfo = null; }
  60818. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  60819. this.particles.push(sp);
  60820. return sp;
  60821. };
  60822. /**
  60823. * Adds some particles to the SPS from the model shape. Returns the shape id.
  60824. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  60825. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  60826. * @param nb (positive integer) the number of particles to be created from this model
  60827. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  60828. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  60829. * @returns the number of shapes in the system
  60830. */
  60831. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  60832. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60833. var meshInd = mesh.getIndices();
  60834. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60835. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60836. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60837. var bbInfo;
  60838. if (this._particlesIntersect) {
  60839. bbInfo = mesh.getBoundingInfo();
  60840. }
  60841. var shape = this._posToShape(meshPos);
  60842. var shapeUV = this._uvsToShapeUV(meshUV);
  60843. var posfunc = options ? options.positionFunction : null;
  60844. var vtxfunc = options ? options.vertexFunction : null;
  60845. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  60846. // particles
  60847. var sp;
  60848. var currentCopy;
  60849. var idx = this.nbParticles;
  60850. for (var i = 0; i < nb; i++) {
  60851. var currentPos = this._positions.length;
  60852. var currentInd = this._indices.length;
  60853. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  60854. if (this._updatable) {
  60855. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  60856. sp.position.copyFrom(currentCopy.position);
  60857. sp.rotation.copyFrom(currentCopy.rotation);
  60858. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  60859. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  60860. }
  60861. if (currentCopy.color && sp.color) {
  60862. sp.color.copyFrom(currentCopy.color);
  60863. }
  60864. sp.scaling.copyFrom(currentCopy.scaling);
  60865. sp.uvs.copyFrom(currentCopy.uvs);
  60866. }
  60867. this._index += shape.length;
  60868. idx++;
  60869. }
  60870. this.nbParticles += nb;
  60871. this._shapeCounter++;
  60872. return this._shapeCounter - 1;
  60873. };
  60874. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  60875. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  60876. this._resetCopy();
  60877. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  60878. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  60879. }
  60880. if (this._copy.rotationQuaternion) {
  60881. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  60882. }
  60883. else {
  60884. this._yaw = this._copy.rotation.y;
  60885. this._pitch = this._copy.rotation.x;
  60886. this._roll = this._copy.rotation.z;
  60887. this._quaternionRotationYPR();
  60888. }
  60889. this._quaternionToRotationMatrix();
  60890. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  60891. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  60892. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  60893. if (this._copy.translateFromPivot) {
  60894. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  60895. }
  60896. else {
  60897. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  60898. }
  60899. this._shape = particle._model._shape;
  60900. for (var pt = 0; pt < this._shape.length; pt++) {
  60901. this._vertex.x = this._shape[pt].x;
  60902. this._vertex.y = this._shape[pt].y;
  60903. this._vertex.z = this._shape[pt].z;
  60904. if (particle._model._vertexFunction) {
  60905. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  60906. }
  60907. this._vertex.x *= this._copy.scaling.x;
  60908. this._vertex.y *= this._copy.scaling.y;
  60909. this._vertex.z *= this._copy.scaling.z;
  60910. this._vertex.x -= this._scaledPivot.x;
  60911. this._vertex.y -= this._scaledPivot.y;
  60912. this._vertex.z -= this._scaledPivot.z;
  60913. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  60914. this._rotated.addInPlace(this._pivotBackTranslation);
  60915. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  60916. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  60917. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  60918. }
  60919. particle.position.x = 0.0;
  60920. particle.position.y = 0.0;
  60921. particle.position.z = 0.0;
  60922. particle.rotation.x = 0.0;
  60923. particle.rotation.y = 0.0;
  60924. particle.rotation.z = 0.0;
  60925. particle.rotationQuaternion = null;
  60926. particle.scaling.x = 1.0;
  60927. particle.scaling.y = 1.0;
  60928. particle.scaling.z = 1.0;
  60929. particle.uvs.x = 0.0;
  60930. particle.uvs.y = 0.0;
  60931. particle.uvs.z = 1.0;
  60932. particle.uvs.w = 1.0;
  60933. particle.pivot.x = 0.0;
  60934. particle.pivot.y = 0.0;
  60935. particle.pivot.z = 0.0;
  60936. particle.translateFromPivot = false;
  60937. particle.parentId = null;
  60938. };
  60939. /**
  60940. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  60941. * @returns the SPS.
  60942. */
  60943. SolidParticleSystem.prototype.rebuildMesh = function () {
  60944. for (var p = 0; p < this.particles.length; p++) {
  60945. this._rebuildParticle(this.particles[p]);
  60946. }
  60947. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  60948. return this;
  60949. };
  60950. /**
  60951. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  60952. * This method calls `updateParticle()` for each particle of the SPS.
  60953. * For an animated SPS, it is usually called within the render loop.
  60954. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  60955. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  60956. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  60957. * @returns the SPS.
  60958. */
  60959. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  60960. if (start === void 0) { start = 0; }
  60961. if (end === void 0) { end = this.nbParticles - 1; }
  60962. if (update === void 0) { update = true; }
  60963. if (!this._updatable) {
  60964. return this;
  60965. }
  60966. // custom beforeUpdate
  60967. this.beforeUpdateParticles(start, end, update);
  60968. this._cam_axisX.x = 1.0;
  60969. this._cam_axisX.y = 0.0;
  60970. this._cam_axisX.z = 0.0;
  60971. this._cam_axisY.x = 0.0;
  60972. this._cam_axisY.y = 1.0;
  60973. this._cam_axisY.z = 0.0;
  60974. this._cam_axisZ.x = 0.0;
  60975. this._cam_axisZ.y = 0.0;
  60976. this._cam_axisZ.z = 1.0;
  60977. // cases when the World Matrix is to be computed first
  60978. if (this.billboard || this._depthSort) {
  60979. this.mesh.computeWorldMatrix(true);
  60980. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  60981. }
  60982. // if the particles will always face the camera
  60983. if (this.billboard) {
  60984. // compute the camera position and un-rotate it by the current mesh rotation
  60985. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  60986. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  60987. this._cam_axisZ.normalize();
  60988. // same for camera up vector extracted from the cam view matrix
  60989. var view = this._camera.getViewMatrix(true);
  60990. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  60991. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  60992. this._cam_axisY.normalize();
  60993. this._cam_axisX.normalize();
  60994. }
  60995. // if depthSort, compute the camera global position in the mesh local system
  60996. if (this._depthSort) {
  60997. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  60998. }
  60999. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61000. var idx = 0; // current position index in the global array positions32
  61001. var index = 0; // position start index in the global array positions32 of the current particle
  61002. var colidx = 0; // current color index in the global array colors32
  61003. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61004. var uvidx = 0; // current uv index in the global array uvs32
  61005. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61006. var pt = 0; // current index in the particle model shape
  61007. if (this.mesh.isFacetDataEnabled) {
  61008. this._computeBoundingBox = true;
  61009. }
  61010. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61011. if (this._computeBoundingBox) {
  61012. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61013. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61014. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61015. }
  61016. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61017. if (this.mesh._boundingInfo) {
  61018. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61019. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61020. }
  61021. }
  61022. }
  61023. // particle loop
  61024. index = this.particles[start]._pos;
  61025. var vpos = (index / 3) | 0;
  61026. colorIndex = vpos * 4;
  61027. uvIndex = vpos * 2;
  61028. for (var p = start; p <= end; p++) {
  61029. this._particle = this.particles[p];
  61030. this._shape = this._particle._model._shape;
  61031. this._shapeUV = this._particle._model._shapeUV;
  61032. // call to custom user function to update the particle properties
  61033. this.updateParticle(this._particle);
  61034. // camera-particle distance for depth sorting
  61035. if (this._depthSort && this._depthSortParticles) {
  61036. var dsp = this.depthSortedParticles[p];
  61037. dsp.ind = this._particle._ind;
  61038. dsp.indicesLength = this._particle._model._indicesLength;
  61039. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61040. }
  61041. // skip the computations for inactive or already invisible particles
  61042. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61043. // increment indexes for the next particle
  61044. pt = this._shape.length;
  61045. index += pt * 3;
  61046. colorIndex += pt * 4;
  61047. uvIndex += pt * 2;
  61048. continue;
  61049. }
  61050. if (this._particle.isVisible) {
  61051. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61052. this._particleHasParent = (this._particle.parentId !== null);
  61053. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61054. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61055. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61056. // particle rotation matrix
  61057. if (this.billboard) {
  61058. this._particle.rotation.x = 0.0;
  61059. this._particle.rotation.y = 0.0;
  61060. }
  61061. if (this._computeParticleRotation || this.billboard) {
  61062. if (this._particle.rotationQuaternion) {
  61063. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61064. }
  61065. else {
  61066. this._yaw = this._particle.rotation.y;
  61067. this._pitch = this._particle.rotation.x;
  61068. this._roll = this._particle.rotation.z;
  61069. this._quaternionRotationYPR();
  61070. }
  61071. this._quaternionToRotationMatrix();
  61072. }
  61073. if (this._particleHasParent) {
  61074. this._parent = this.particles[this._particle.parentId];
  61075. 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];
  61076. 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];
  61077. 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];
  61078. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61079. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61080. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61081. if (this._computeParticleRotation || this.billboard) {
  61082. 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];
  61083. 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];
  61084. 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];
  61085. 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];
  61086. 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];
  61087. 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];
  61088. 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];
  61089. 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];
  61090. 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];
  61091. }
  61092. }
  61093. else {
  61094. this._particle._globalPosition.x = this._particle.position.x;
  61095. this._particle._globalPosition.y = this._particle.position.y;
  61096. this._particle._globalPosition.z = this._particle.position.z;
  61097. if (this._computeParticleRotation || this.billboard) {
  61098. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61099. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61100. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61101. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61102. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61103. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61104. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61105. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61106. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61107. }
  61108. }
  61109. if (this._particle.translateFromPivot) {
  61110. this._pivotBackTranslation.x = 0.0;
  61111. this._pivotBackTranslation.y = 0.0;
  61112. this._pivotBackTranslation.z = 0.0;
  61113. }
  61114. else {
  61115. this._pivotBackTranslation.x = this._scaledPivot.x;
  61116. this._pivotBackTranslation.y = this._scaledPivot.y;
  61117. this._pivotBackTranslation.z = this._scaledPivot.z;
  61118. }
  61119. // particle vertex loop
  61120. for (pt = 0; pt < this._shape.length; pt++) {
  61121. idx = index + pt * 3;
  61122. colidx = colorIndex + pt * 4;
  61123. uvidx = uvIndex + pt * 2;
  61124. this._vertex.x = this._shape[pt].x;
  61125. this._vertex.y = this._shape[pt].y;
  61126. this._vertex.z = this._shape[pt].z;
  61127. if (this._computeParticleVertex) {
  61128. this.updateParticleVertex(this._particle, this._vertex, pt);
  61129. }
  61130. // positions
  61131. this._vertex.x *= this._particle.scaling.x;
  61132. this._vertex.y *= this._particle.scaling.y;
  61133. this._vertex.z *= this._particle.scaling.z;
  61134. this._vertex.x -= this._scaledPivot.x;
  61135. this._vertex.y -= this._scaledPivot.y;
  61136. this._vertex.z -= this._scaledPivot.z;
  61137. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61138. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61139. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61140. this._rotated.x += this._pivotBackTranslation.x;
  61141. this._rotated.y += this._pivotBackTranslation.y;
  61142. this._rotated.z += this._pivotBackTranslation.z;
  61143. 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;
  61144. 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;
  61145. 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;
  61146. if (this._computeBoundingBox) {
  61147. if (this._positions32[idx] < this._minimum.x) {
  61148. this._minimum.x = this._positions32[idx];
  61149. }
  61150. if (this._positions32[idx] > this._maximum.x) {
  61151. this._maximum.x = this._positions32[idx];
  61152. }
  61153. if (this._positions32[idx + 1] < this._minimum.y) {
  61154. this._minimum.y = this._positions32[idx + 1];
  61155. }
  61156. if (this._positions32[idx + 1] > this._maximum.y) {
  61157. this._maximum.y = this._positions32[idx + 1];
  61158. }
  61159. if (this._positions32[idx + 2] < this._minimum.z) {
  61160. this._minimum.z = this._positions32[idx + 2];
  61161. }
  61162. if (this._positions32[idx + 2] > this._maximum.z) {
  61163. this._maximum.z = this._positions32[idx + 2];
  61164. }
  61165. }
  61166. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61167. if (!this._computeParticleVertex) {
  61168. this._normal.x = this._fixedNormal32[idx];
  61169. this._normal.y = this._fixedNormal32[idx + 1];
  61170. this._normal.z = this._fixedNormal32[idx + 2];
  61171. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61172. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61173. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61174. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61175. 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;
  61176. 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;
  61177. }
  61178. if (this._computeParticleColor && this._particle.color) {
  61179. this._colors32[colidx] = this._particle.color.r;
  61180. this._colors32[colidx + 1] = this._particle.color.g;
  61181. this._colors32[colidx + 2] = this._particle.color.b;
  61182. this._colors32[colidx + 3] = this._particle.color.a;
  61183. }
  61184. if (this._computeParticleTexture) {
  61185. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61186. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61187. }
  61188. }
  61189. }
  61190. // particle just set invisible : scaled to zero and positioned at the origin
  61191. else {
  61192. this._particle._stillInvisible = true; // mark the particle as invisible
  61193. for (pt = 0; pt < this._shape.length; pt++) {
  61194. idx = index + pt * 3;
  61195. colidx = colorIndex + pt * 4;
  61196. uvidx = uvIndex + pt * 2;
  61197. this._positions32[idx] = 0.0;
  61198. this._positions32[idx + 1] = 0.0;
  61199. this._positions32[idx + 2] = 0.0;
  61200. this._normals32[idx] = 0.0;
  61201. this._normals32[idx + 1] = 0.0;
  61202. this._normals32[idx + 2] = 0.0;
  61203. if (this._computeParticleColor && this._particle.color) {
  61204. this._colors32[colidx] = this._particle.color.r;
  61205. this._colors32[colidx + 1] = this._particle.color.g;
  61206. this._colors32[colidx + 2] = this._particle.color.b;
  61207. this._colors32[colidx + 3] = this._particle.color.a;
  61208. }
  61209. if (this._computeParticleTexture) {
  61210. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61211. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61212. }
  61213. }
  61214. }
  61215. // if the particle intersections must be computed : update the bbInfo
  61216. if (this._particlesIntersect) {
  61217. var bInfo = this._particle._boundingInfo;
  61218. var bBox = bInfo.boundingBox;
  61219. var bSphere = bInfo.boundingSphere;
  61220. if (!this._bSphereOnly) {
  61221. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61222. for (var b = 0; b < bBox.vectors.length; b++) {
  61223. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61224. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61225. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61226. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61227. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61228. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61229. 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;
  61230. 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;
  61231. 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;
  61232. }
  61233. bBox._update(this.mesh._worldMatrix);
  61234. }
  61235. // place and scale the particle bouding sphere in the SPS local system, then update it
  61236. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61237. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61238. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61239. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61240. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61241. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61242. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61243. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61244. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61245. 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));
  61246. bSphere._update(this.mesh._worldMatrix);
  61247. }
  61248. // increment indexes for the next particle
  61249. index = idx + 3;
  61250. colorIndex = colidx + 4;
  61251. uvIndex = uvidx + 2;
  61252. }
  61253. // if the VBO must be updated
  61254. if (update) {
  61255. if (this._computeParticleColor) {
  61256. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61257. }
  61258. if (this._computeParticleTexture) {
  61259. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61260. }
  61261. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61262. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61263. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61264. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61265. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61266. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61267. for (var i = 0; i < this._normals32.length; i++) {
  61268. this._fixedNormal32[i] = this._normals32[i];
  61269. }
  61270. }
  61271. if (!this.mesh.areNormalsFrozen) {
  61272. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61273. }
  61274. }
  61275. if (this._depthSort && this._depthSortParticles) {
  61276. this.depthSortedParticles.sort(this._depthSortFunction);
  61277. var dspl = this.depthSortedParticles.length;
  61278. var sorted = 0;
  61279. var lind = 0;
  61280. var sind = 0;
  61281. var sid = 0;
  61282. for (sorted = 0; sorted < dspl; sorted++) {
  61283. lind = this.depthSortedParticles[sorted].indicesLength;
  61284. sind = this.depthSortedParticles[sorted].ind;
  61285. for (var i = 0; i < lind; i++) {
  61286. this._indices32[sid] = this._indices[sind + i];
  61287. sid++;
  61288. }
  61289. }
  61290. this.mesh.updateIndices(this._indices32);
  61291. }
  61292. }
  61293. if (this._computeBoundingBox) {
  61294. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  61295. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  61296. }
  61297. this.afterUpdateParticles(start, end, update);
  61298. return this;
  61299. };
  61300. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  61301. this._halfroll = this._roll * 0.5;
  61302. this._halfpitch = this._pitch * 0.5;
  61303. this._halfyaw = this._yaw * 0.5;
  61304. this._sinRoll = Math.sin(this._halfroll);
  61305. this._cosRoll = Math.cos(this._halfroll);
  61306. this._sinPitch = Math.sin(this._halfpitch);
  61307. this._cosPitch = Math.cos(this._halfpitch);
  61308. this._sinYaw = Math.sin(this._halfyaw);
  61309. this._cosYaw = Math.cos(this._halfyaw);
  61310. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  61311. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  61312. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  61313. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  61314. };
  61315. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  61316. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  61317. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  61318. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  61319. this._rotMatrix.m[3] = 0;
  61320. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  61321. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  61322. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  61323. this._rotMatrix.m[7] = 0;
  61324. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  61325. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  61326. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  61327. this._rotMatrix.m[11] = 0;
  61328. this._rotMatrix.m[12] = 0;
  61329. this._rotMatrix.m[13] = 0;
  61330. this._rotMatrix.m[14] = 0;
  61331. this._rotMatrix.m[15] = 1.0;
  61332. };
  61333. /**
  61334. * Disposes the SPS.
  61335. */
  61336. SolidParticleSystem.prototype.dispose = function () {
  61337. this.mesh.dispose();
  61338. this.vars = null;
  61339. // drop references to internal big arrays for the GC
  61340. this._positions = null;
  61341. this._indices = null;
  61342. this._normals = null;
  61343. this._uvs = null;
  61344. this._colors = null;
  61345. this._indices32 = null;
  61346. this._positions32 = null;
  61347. this._normals32 = null;
  61348. this._fixedNormal32 = null;
  61349. this._uvs32 = null;
  61350. this._colors32 = null;
  61351. this.pickedParticles = null;
  61352. };
  61353. /**
  61354. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  61355. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61356. * @returns the SPS.
  61357. */
  61358. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  61359. if (!this._isVisibilityBoxLocked) {
  61360. this.mesh.refreshBoundingInfo();
  61361. }
  61362. return this;
  61363. };
  61364. /**
  61365. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  61366. * @param size the size (float) of the visibility box
  61367. * note : this doesn't lock the SPS mesh bounding box.
  61368. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61369. */
  61370. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  61371. var vis = size / 2;
  61372. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  61373. };
  61374. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  61375. /**
  61376. * Gets whether the SPS as always visible or not
  61377. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61378. */
  61379. get: function () {
  61380. return this._alwaysVisible;
  61381. },
  61382. /**
  61383. * Sets the SPS as always visible or not
  61384. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61385. */
  61386. set: function (val) {
  61387. this._alwaysVisible = val;
  61388. this.mesh.alwaysSelectAsActiveMesh = val;
  61389. },
  61390. enumerable: true,
  61391. configurable: true
  61392. });
  61393. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  61394. /**
  61395. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61396. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61397. */
  61398. get: function () {
  61399. return this._isVisibilityBoxLocked;
  61400. },
  61401. /**
  61402. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61403. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61404. */
  61405. set: function (val) {
  61406. this._isVisibilityBoxLocked = val;
  61407. var boundingInfo = this.mesh.getBoundingInfo();
  61408. boundingInfo.isLocked = val;
  61409. },
  61410. enumerable: true,
  61411. configurable: true
  61412. });
  61413. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  61414. /**
  61415. * Gets if `setParticles()` computes the particle rotations or not.
  61416. * Default value : true. The SPS is faster when it's set to false.
  61417. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61418. */
  61419. get: function () {
  61420. return this._computeParticleRotation;
  61421. },
  61422. /**
  61423. * Tells to `setParticles()` to compute the particle rotations or not.
  61424. * Default value : true. The SPS is faster when it's set to false.
  61425. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61426. */
  61427. set: function (val) {
  61428. this._computeParticleRotation = val;
  61429. },
  61430. enumerable: true,
  61431. configurable: true
  61432. });
  61433. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  61434. /**
  61435. * Gets if `setParticles()` computes the particle colors or not.
  61436. * Default value : true. The SPS is faster when it's set to false.
  61437. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61438. */
  61439. get: function () {
  61440. return this._computeParticleColor;
  61441. },
  61442. /**
  61443. * Tells to `setParticles()` to compute the particle colors or not.
  61444. * Default value : true. The SPS is faster when it's set to false.
  61445. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61446. */
  61447. set: function (val) {
  61448. this._computeParticleColor = val;
  61449. },
  61450. enumerable: true,
  61451. configurable: true
  61452. });
  61453. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  61454. /**
  61455. * Gets if `setParticles()` computes the particle textures or not.
  61456. * Default value : true. The SPS is faster when it's set to false.
  61457. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  61458. */
  61459. get: function () {
  61460. return this._computeParticleTexture;
  61461. },
  61462. set: function (val) {
  61463. this._computeParticleTexture = val;
  61464. },
  61465. enumerable: true,
  61466. configurable: true
  61467. });
  61468. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  61469. /**
  61470. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  61471. * Default value : false. The SPS is faster when it's set to false.
  61472. * Note : the particle custom vertex positions aren't stored values.
  61473. */
  61474. get: function () {
  61475. return this._computeParticleVertex;
  61476. },
  61477. /**
  61478. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  61479. * Default value : false. The SPS is faster when it's set to false.
  61480. * Note : the particle custom vertex positions aren't stored values.
  61481. */
  61482. set: function (val) {
  61483. this._computeParticleVertex = val;
  61484. },
  61485. enumerable: true,
  61486. configurable: true
  61487. });
  61488. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  61489. /**
  61490. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  61491. */
  61492. get: function () {
  61493. return this._computeBoundingBox;
  61494. },
  61495. /**
  61496. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  61497. */
  61498. set: function (val) {
  61499. this._computeBoundingBox = val;
  61500. },
  61501. enumerable: true,
  61502. configurable: true
  61503. });
  61504. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  61505. /**
  61506. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  61507. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61508. * Default : `true`
  61509. */
  61510. get: function () {
  61511. return this._depthSortParticles;
  61512. },
  61513. /**
  61514. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  61515. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61516. * Default : `true`
  61517. */
  61518. set: function (val) {
  61519. this._depthSortParticles = val;
  61520. },
  61521. enumerable: true,
  61522. configurable: true
  61523. });
  61524. // =======================================================================
  61525. // Particle behavior logic
  61526. // these following methods may be overwritten by the user to fit his needs
  61527. /**
  61528. * This function does nothing. It may be overwritten to set all the particle first values.
  61529. * The SPS doesn't call this function, you may have to call it by your own.
  61530. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61531. */
  61532. SolidParticleSystem.prototype.initParticles = function () {
  61533. };
  61534. /**
  61535. * This function does nothing. It may be overwritten to recycle a particle.
  61536. * The SPS doesn't call this function, you may have to call it by your own.
  61537. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61538. * @param particle The particle to recycle
  61539. * @returns the recycled particle
  61540. */
  61541. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  61542. return particle;
  61543. };
  61544. /**
  61545. * Updates a particle : this function should be overwritten by the user.
  61546. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  61547. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61548. * @example : just set a particle position or velocity and recycle conditions
  61549. * @param particle The particle to update
  61550. * @returns the updated particle
  61551. */
  61552. SolidParticleSystem.prototype.updateParticle = function (particle) {
  61553. return particle;
  61554. };
  61555. /**
  61556. * Updates a vertex of a particle : it can be overwritten by the user.
  61557. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  61558. * @param particle the current particle
  61559. * @param vertex the current index of the current particle
  61560. * @param pt the index of the current vertex in the particle shape
  61561. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  61562. * @example : just set a vertex particle position
  61563. * @returns the updated vertex
  61564. */
  61565. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  61566. return vertex;
  61567. };
  61568. /**
  61569. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  61570. * This does nothing and may be overwritten by the user.
  61571. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61572. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61573. * @param update the boolean update value actually passed to setParticles()
  61574. */
  61575. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  61576. };
  61577. /**
  61578. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  61579. * This will be passed three parameters.
  61580. * This does nothing and may be overwritten by the user.
  61581. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61582. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61583. * @param update the boolean update value actually passed to setParticles()
  61584. */
  61585. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  61586. };
  61587. return SolidParticleSystem;
  61588. }());
  61589. BABYLON.SolidParticleSystem = SolidParticleSystem;
  61590. })(BABYLON || (BABYLON = {}));
  61591. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  61592. var BABYLON;
  61593. (function (BABYLON) {
  61594. /**
  61595. * Class containing static functions to help procedurally build meshes
  61596. */
  61597. var MeshBuilder = /** @class */ (function () {
  61598. function MeshBuilder() {
  61599. }
  61600. MeshBuilder.updateSideOrientation = function (orientation) {
  61601. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61602. return BABYLON.Mesh.DOUBLESIDE;
  61603. }
  61604. if (orientation === undefined || orientation === null) {
  61605. return BABYLON.Mesh.FRONTSIDE;
  61606. }
  61607. return orientation;
  61608. };
  61609. /**
  61610. * Creates a box mesh
  61611. * * The parameter `size` sets the size (float) of each box side (default 1)
  61612. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61613. * * 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)
  61614. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61615. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61616. * * 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
  61617. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61618. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61619. * @param name defines the name of the mesh
  61620. * @param options defines the options used to create the mesh
  61621. * @param scene defines the hosting scene
  61622. * @returns the box mesh
  61623. */
  61624. MeshBuilder.CreateBox = function (name, options, scene) {
  61625. if (scene === void 0) { scene = null; }
  61626. var box = new BABYLON.Mesh(name, scene);
  61627. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61628. box._originalBuilderSideOrientation = options.sideOrientation;
  61629. var vertexData = BABYLON.VertexData.CreateBox(options);
  61630. vertexData.applyToMesh(box, options.updatable);
  61631. return box;
  61632. };
  61633. /**
  61634. * Creates a sphere mesh
  61635. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61636. * * 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`)
  61637. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61638. * * 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
  61639. * * 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)
  61640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61641. * * 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
  61642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61643. * @param name defines the name of the mesh
  61644. * @param options defines the options used to create the mesh
  61645. * @param scene defines the hosting scene
  61646. * @returns the sphere mesh
  61647. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61648. */
  61649. MeshBuilder.CreateSphere = function (name, options, scene) {
  61650. var sphere = new BABYLON.Mesh(name, scene);
  61651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61652. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61653. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61654. vertexData.applyToMesh(sphere, options.updatable);
  61655. return sphere;
  61656. };
  61657. /**
  61658. * Creates a plane polygonal mesh. By default, this is a disc
  61659. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61660. * * 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
  61661. * * 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
  61662. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61663. * * 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
  61664. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61665. * @param name defines the name of the mesh
  61666. * @param options defines the options used to create the mesh
  61667. * @param scene defines the hosting scene
  61668. * @returns the plane polygonal mesh
  61669. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61670. */
  61671. MeshBuilder.CreateDisc = function (name, options, scene) {
  61672. if (scene === void 0) { scene = null; }
  61673. var disc = new BABYLON.Mesh(name, scene);
  61674. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61675. disc._originalBuilderSideOrientation = options.sideOrientation;
  61676. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61677. vertexData.applyToMesh(disc, options.updatable);
  61678. return disc;
  61679. };
  61680. /**
  61681. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61682. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61683. * * 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`)
  61684. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61685. * * 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
  61686. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61687. * * 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
  61688. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61689. * @param name defines the name of the mesh
  61690. * @param options defines the options used to create the mesh
  61691. * @param scene defines the hosting scene
  61692. * @returns the icosahedron mesh
  61693. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61694. */
  61695. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61696. var sphere = new BABYLON.Mesh(name, scene);
  61697. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61698. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61699. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61700. vertexData.applyToMesh(sphere, options.updatable);
  61701. return sphere;
  61702. };
  61703. ;
  61704. /**
  61705. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61706. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61707. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61708. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61709. * * 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
  61710. * * 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
  61711. * * 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
  61712. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61713. * * 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
  61714. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61715. * * 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
  61716. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61717. * * 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
  61718. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61719. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61720. * @param name defines the name of the mesh
  61721. * @param options defines the options used to create the mesh
  61722. * @param scene defines the hosting scene
  61723. * @returns the ribbon mesh
  61724. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61725. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61726. */
  61727. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61728. if (scene === void 0) { scene = null; }
  61729. var pathArray = options.pathArray;
  61730. var closeArray = options.closeArray;
  61731. var closePath = options.closePath;
  61732. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61733. var instance = options.instance;
  61734. var updatable = options.updatable;
  61735. if (instance) { // existing ribbon instance update
  61736. // positionFunction : ribbon case
  61737. // only pathArray and sideOrientation parameters are taken into account for positions update
  61738. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61739. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61740. var positionFunction = function (positions) {
  61741. var minlg = pathArray[0].length;
  61742. var i = 0;
  61743. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61744. for (var si = 1; si <= ns; si++) {
  61745. for (var p = 0; p < pathArray.length; p++) {
  61746. var path = pathArray[p];
  61747. var l = path.length;
  61748. minlg = (minlg < l) ? minlg : l;
  61749. var j = 0;
  61750. while (j < minlg) {
  61751. positions[i] = path[j].x;
  61752. positions[i + 1] = path[j].y;
  61753. positions[i + 2] = path[j].z;
  61754. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61755. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61756. }
  61757. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61758. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61759. }
  61760. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61761. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61762. }
  61763. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61764. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61765. }
  61766. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61767. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61768. }
  61769. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61770. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61771. }
  61772. j++;
  61773. i += 3;
  61774. }
  61775. if (instance._closePath) {
  61776. positions[i] = path[0].x;
  61777. positions[i + 1] = path[0].y;
  61778. positions[i + 2] = path[0].z;
  61779. i += 3;
  61780. }
  61781. }
  61782. }
  61783. };
  61784. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61785. positionFunction(positions);
  61786. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61787. instance._boundingInfo.update(instance._worldMatrix);
  61788. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61789. if (options.colors) {
  61790. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61791. for (var c = 0; c < options.colors.length; c++) {
  61792. colors[c * 4] = options.colors[c].r;
  61793. colors[c * 4 + 1] = options.colors[c].g;
  61794. colors[c * 4 + 2] = options.colors[c].b;
  61795. colors[c * 4 + 3] = options.colors[c].a;
  61796. }
  61797. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61798. }
  61799. if (options.uvs) {
  61800. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61801. for (var i = 0; i < options.uvs.length; i++) {
  61802. uvs[i * 2] = options.uvs[i].x;
  61803. uvs[i * 2 + 1] = options.uvs[i].y;
  61804. }
  61805. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61806. }
  61807. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61808. var indices = instance.getIndices();
  61809. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61810. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61811. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61812. if (instance._closePath) {
  61813. var indexFirst = 0;
  61814. var indexLast = 0;
  61815. for (var p = 0; p < pathArray.length; p++) {
  61816. indexFirst = instance._idx[p] * 3;
  61817. if (p + 1 < pathArray.length) {
  61818. indexLast = (instance._idx[p + 1] - 1) * 3;
  61819. }
  61820. else {
  61821. indexLast = normals.length - 3;
  61822. }
  61823. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61824. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61825. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61826. normals[indexLast] = normals[indexFirst];
  61827. normals[indexLast + 1] = normals[indexFirst + 1];
  61828. normals[indexLast + 2] = normals[indexFirst + 2];
  61829. }
  61830. }
  61831. if (!(instance.areNormalsFrozen)) {
  61832. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61833. }
  61834. }
  61835. return instance;
  61836. }
  61837. else { // new ribbon creation
  61838. var ribbon = new BABYLON.Mesh(name, scene);
  61839. ribbon._originalBuilderSideOrientation = sideOrientation;
  61840. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61841. if (closePath) {
  61842. ribbon._idx = vertexData._idx;
  61843. }
  61844. ribbon._closePath = closePath;
  61845. ribbon._closeArray = closeArray;
  61846. vertexData.applyToMesh(ribbon, updatable);
  61847. return ribbon;
  61848. }
  61849. };
  61850. /**
  61851. * Creates a cylinder or a cone mesh
  61852. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61853. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61854. * * 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.
  61855. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61856. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61857. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61858. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61859. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61860. * * 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).
  61861. * * 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
  61862. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61863. * * 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
  61864. * * 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.
  61865. * * If `enclose` is false, a ring surface is one element.
  61866. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61867. * * 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
  61868. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61869. * * 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
  61870. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61871. * @param name defines the name of the mesh
  61872. * @param options defines the options used to create the mesh
  61873. * @param scene defines the hosting scene
  61874. * @returns the cylinder mesh
  61875. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61876. */
  61877. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61878. var cylinder = new BABYLON.Mesh(name, scene);
  61879. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61880. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61881. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61882. vertexData.applyToMesh(cylinder, options.updatable);
  61883. return cylinder;
  61884. };
  61885. /**
  61886. * Creates a torus mesh
  61887. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61888. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61889. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61890. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61891. * * 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
  61892. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61893. * @param name defines the name of the mesh
  61894. * @param options defines the options used to create the mesh
  61895. * @param scene defines the hosting scene
  61896. * @returns the torus mesh
  61897. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61898. */
  61899. MeshBuilder.CreateTorus = function (name, options, scene) {
  61900. var torus = new BABYLON.Mesh(name, scene);
  61901. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61902. torus._originalBuilderSideOrientation = options.sideOrientation;
  61903. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61904. vertexData.applyToMesh(torus, options.updatable);
  61905. return torus;
  61906. };
  61907. /**
  61908. * Creates a torus knot mesh
  61909. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61910. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61911. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61912. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61913. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61914. * * 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
  61915. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61916. * @param name defines the name of the mesh
  61917. * @param options defines the options used to create the mesh
  61918. * @param scene defines the hosting scene
  61919. * @returns the torus knot mesh
  61920. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61921. */
  61922. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61923. var torusKnot = new BABYLON.Mesh(name, scene);
  61924. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61925. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61926. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61927. vertexData.applyToMesh(torusKnot, options.updatable);
  61928. return torusKnot;
  61929. };
  61930. /**
  61931. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61932. * * 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
  61933. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61934. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61935. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61936. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61937. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61938. * * 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
  61939. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61940. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61941. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61942. * @param name defines the name of the new line system
  61943. * @param options defines the options used to create the line system
  61944. * @param scene defines the hosting scene
  61945. * @returns a new line system mesh
  61946. */
  61947. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61948. var instance = options.instance;
  61949. var lines = options.lines;
  61950. var colors = options.colors;
  61951. if (instance) { // lines update
  61952. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61953. var vertexColor;
  61954. var lineColors;
  61955. if (colors) {
  61956. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61957. }
  61958. var i = 0;
  61959. var c = 0;
  61960. for (var l = 0; l < lines.length; l++) {
  61961. var points = lines[l];
  61962. for (var p = 0; p < points.length; p++) {
  61963. positions[i] = points[p].x;
  61964. positions[i + 1] = points[p].y;
  61965. positions[i + 2] = points[p].z;
  61966. if (colors && vertexColor) {
  61967. lineColors = colors[l];
  61968. vertexColor[c] = lineColors[p].r;
  61969. vertexColor[c + 1] = lineColors[p].g;
  61970. vertexColor[c + 2] = lineColors[p].b;
  61971. vertexColor[c + 3] = lineColors[p].a;
  61972. c += 4;
  61973. }
  61974. i += 3;
  61975. }
  61976. }
  61977. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61978. if (colors && vertexColor) {
  61979. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61980. }
  61981. return instance;
  61982. }
  61983. // line system creation
  61984. var useVertexColor = (colors) ? true : false;
  61985. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61986. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61987. vertexData.applyToMesh(lineSystem, options.updatable);
  61988. return lineSystem;
  61989. };
  61990. /**
  61991. * Creates a line mesh
  61992. * 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
  61993. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61994. * * The parameter `points` is an array successive Vector3
  61995. * * 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
  61996. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61997. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61998. * * When updating an instance, remember that only point positions can change, not the number of points
  61999. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62000. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62001. * @param name defines the name of the new line system
  62002. * @param options defines the options used to create the line system
  62003. * @param scene defines the hosting scene
  62004. * @returns a new line mesh
  62005. */
  62006. MeshBuilder.CreateLines = function (name, options, scene) {
  62007. if (scene === void 0) { scene = null; }
  62008. var colors = (options.colors) ? [options.colors] : null;
  62009. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62010. return lines;
  62011. };
  62012. /**
  62013. * Creates a dashed line mesh
  62014. * * 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
  62015. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62016. * * The parameter `points` is an array successive Vector3
  62017. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62018. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62019. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62020. * * 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
  62021. * * When updating an instance, remember that only point positions can change, not the number of points
  62022. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62023. * @param name defines the name of the mesh
  62024. * @param options defines the options used to create the mesh
  62025. * @param scene defines the hosting scene
  62026. * @returns the dashed line mesh
  62027. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62028. */
  62029. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62030. if (scene === void 0) { scene = null; }
  62031. var points = options.points;
  62032. var instance = options.instance;
  62033. var gapSize = options.gapSize || 1;
  62034. var dashSize = options.dashSize || 3;
  62035. if (instance) { // dashed lines update
  62036. var positionFunction = function (positions) {
  62037. var curvect = BABYLON.Vector3.Zero();
  62038. var nbSeg = positions.length / 6;
  62039. var lg = 0;
  62040. var nb = 0;
  62041. var shft = 0;
  62042. var dashshft = 0;
  62043. var curshft = 0;
  62044. var p = 0;
  62045. var i = 0;
  62046. var j = 0;
  62047. for (i = 0; i < points.length - 1; i++) {
  62048. points[i + 1].subtractToRef(points[i], curvect);
  62049. lg += curvect.length();
  62050. }
  62051. shft = lg / nbSeg;
  62052. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62053. for (i = 0; i < points.length - 1; i++) {
  62054. points[i + 1].subtractToRef(points[i], curvect);
  62055. nb = Math.floor(curvect.length() / shft);
  62056. curvect.normalize();
  62057. j = 0;
  62058. while (j < nb && p < positions.length) {
  62059. curshft = shft * j;
  62060. positions[p] = points[i].x + curshft * curvect.x;
  62061. positions[p + 1] = points[i].y + curshft * curvect.y;
  62062. positions[p + 2] = points[i].z + curshft * curvect.z;
  62063. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62064. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62065. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62066. p += 6;
  62067. j++;
  62068. }
  62069. }
  62070. while (p < positions.length) {
  62071. positions[p] = points[i].x;
  62072. positions[p + 1] = points[i].y;
  62073. positions[p + 2] = points[i].z;
  62074. p += 3;
  62075. }
  62076. };
  62077. instance.updateMeshPositions(positionFunction, false);
  62078. return instance;
  62079. }
  62080. // dashed lines creation
  62081. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62082. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62083. vertexData.applyToMesh(dashedLines, options.updatable);
  62084. dashedLines.dashSize = dashSize;
  62085. dashedLines.gapSize = gapSize;
  62086. return dashedLines;
  62087. };
  62088. /**
  62089. * 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.
  62090. * * 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.
  62091. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62092. * * 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.
  62093. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62094. * * 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
  62095. * * 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
  62096. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62097. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62098. * * 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
  62099. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62100. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62101. * @param name defines the name of the mesh
  62102. * @param options defines the options used to create the mesh
  62103. * @param scene defines the hosting scene
  62104. * @returns the extruded shape mesh
  62105. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62106. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62107. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62108. */
  62109. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62110. if (scene === void 0) { scene = null; }
  62111. var path = options.path;
  62112. var shape = options.shape;
  62113. var scale = options.scale || 1;
  62114. var rotation = options.rotation || 0;
  62115. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62116. var updatable = options.updatable;
  62117. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62118. var instance = options.instance || null;
  62119. var invertUV = options.invertUV || false;
  62120. 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);
  62121. };
  62122. /**
  62123. * Creates an custom extruded shape mesh.
  62124. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62125. * * 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.
  62126. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62127. * * 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
  62128. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62129. * * 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
  62130. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62131. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62132. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62133. * * 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
  62134. * * 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
  62135. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62136. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62137. * * 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
  62138. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62139. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62140. * @param name defines the name of the mesh
  62141. * @param options defines the options used to create the mesh
  62142. * @param scene defines the hosting scene
  62143. * @returns the custom extruded shape mesh
  62144. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62145. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62146. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62147. */
  62148. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62149. var path = options.path;
  62150. var shape = options.shape;
  62151. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62152. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62153. var ribbonCloseArray = options.ribbonCloseArray || false;
  62154. var ribbonClosePath = options.ribbonClosePath || false;
  62155. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62156. var updatable = options.updatable;
  62157. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62158. var instance = options.instance;
  62159. var invertUV = options.invertUV || false;
  62160. 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);
  62161. };
  62162. /**
  62163. * Creates lathe mesh.
  62164. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62165. * * 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
  62166. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62167. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62168. * * 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
  62169. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62170. * * 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
  62171. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62172. * * 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
  62173. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62174. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62175. * @param name defines the name of the mesh
  62176. * @param options defines the options used to create the mesh
  62177. * @param scene defines the hosting scene
  62178. * @returns the lathe mesh
  62179. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62180. */
  62181. MeshBuilder.CreateLathe = function (name, options, scene) {
  62182. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62183. var closed = (options.closed === undefined) ? true : options.closed;
  62184. var shape = options.shape;
  62185. var radius = options.radius || 1;
  62186. var tessellation = options.tessellation || 64;
  62187. var updatable = options.updatable;
  62188. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62189. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62190. var pi2 = Math.PI * 2;
  62191. var paths = new Array();
  62192. var invertUV = options.invertUV || false;
  62193. var i = 0;
  62194. var p = 0;
  62195. var step = pi2 / tessellation * arc;
  62196. var rotated;
  62197. var path = new Array();
  62198. for (i = 0; i <= tessellation; i++) {
  62199. var path = [];
  62200. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62201. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62202. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62203. }
  62204. for (p = 0; p < shape.length; p++) {
  62205. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62206. path.push(rotated);
  62207. }
  62208. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62209. 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));
  62210. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62211. }
  62212. paths.push(path);
  62213. }
  62214. // lathe ribbon
  62215. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62216. return lathe;
  62217. };
  62218. /**
  62219. * Creates a plane mesh
  62220. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62221. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62222. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62223. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62224. * * 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
  62225. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62226. * @param name defines the name of the mesh
  62227. * @param options defines the options used to create the mesh
  62228. * @param scene defines the hosting scene
  62229. * @returns the plane mesh
  62230. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62231. */
  62232. MeshBuilder.CreatePlane = function (name, options, scene) {
  62233. var plane = new BABYLON.Mesh(name, scene);
  62234. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62235. plane._originalBuilderSideOrientation = options.sideOrientation;
  62236. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62237. vertexData.applyToMesh(plane, options.updatable);
  62238. if (options.sourcePlane) {
  62239. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62240. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62241. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62242. plane.rotate(vectorProduct, product);
  62243. }
  62244. return plane;
  62245. };
  62246. /**
  62247. * Creates a ground mesh
  62248. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62249. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62250. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62251. * @param name defines the name of the mesh
  62252. * @param options defines the options used to create the mesh
  62253. * @param scene defines the hosting scene
  62254. * @returns the ground mesh
  62255. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62256. */
  62257. MeshBuilder.CreateGround = function (name, options, scene) {
  62258. var ground = new BABYLON.GroundMesh(name, scene);
  62259. ground._setReady(false);
  62260. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62261. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62262. ground._width = options.width || 1;
  62263. ground._height = options.height || 1;
  62264. ground._maxX = ground._width / 2;
  62265. ground._maxZ = ground._height / 2;
  62266. ground._minX = -ground._maxX;
  62267. ground._minZ = -ground._maxZ;
  62268. var vertexData = BABYLON.VertexData.CreateGround(options);
  62269. vertexData.applyToMesh(ground, options.updatable);
  62270. ground._setReady(true);
  62271. return ground;
  62272. };
  62273. /**
  62274. * Creates a tiled ground mesh
  62275. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62276. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62277. * * 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
  62278. * * 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
  62279. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62280. * @param name defines the name of the mesh
  62281. * @param options defines the options used to create the mesh
  62282. * @param scene defines the hosting scene
  62283. * @returns the tiled ground mesh
  62284. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62285. */
  62286. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  62287. var tiledGround = new BABYLON.Mesh(name, scene);
  62288. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  62289. vertexData.applyToMesh(tiledGround, options.updatable);
  62290. return tiledGround;
  62291. };
  62292. /**
  62293. * Creates a ground mesh from a height map
  62294. * * The parameter `url` sets the URL of the height map image resource.
  62295. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  62296. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  62297. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  62298. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  62299. * * 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.
  62300. * * 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).
  62301. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62302. * @param name defines the name of the mesh
  62303. * @param url defines the url to the height map
  62304. * @param options defines the options used to create the mesh
  62305. * @param scene defines the hosting scene
  62306. * @returns the ground mesh
  62307. * @see http://doc.babylonjs.com/babylon101/height_map
  62308. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  62309. */
  62310. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  62311. var width = options.width || 10.0;
  62312. var height = options.height || 10.0;
  62313. var subdivisions = options.subdivisions || 1 | 0;
  62314. var minHeight = options.minHeight || 0.0;
  62315. var maxHeight = options.maxHeight || 1.0;
  62316. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  62317. var updatable = options.updatable;
  62318. var onReady = options.onReady;
  62319. var ground = new BABYLON.GroundMesh(name, scene);
  62320. ground._subdivisionsX = subdivisions;
  62321. ground._subdivisionsY = subdivisions;
  62322. ground._width = width;
  62323. ground._height = height;
  62324. ground._maxX = ground._width / 2.0;
  62325. ground._maxZ = ground._height / 2.0;
  62326. ground._minX = -ground._maxX;
  62327. ground._minZ = -ground._maxZ;
  62328. ground._setReady(false);
  62329. var onload = function (img) {
  62330. // Getting height map data
  62331. var canvas = document.createElement("canvas");
  62332. var context = canvas.getContext("2d");
  62333. if (!context) {
  62334. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  62335. }
  62336. if (scene.isDisposed) {
  62337. return;
  62338. }
  62339. var bufferWidth = img.width;
  62340. var bufferHeight = img.height;
  62341. canvas.width = bufferWidth;
  62342. canvas.height = bufferHeight;
  62343. context.drawImage(img, 0, 0);
  62344. // Create VertexData from map data
  62345. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  62346. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  62347. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  62348. width: width, height: height,
  62349. subdivisions: subdivisions,
  62350. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  62351. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  62352. });
  62353. vertexData.applyToMesh(ground, updatable);
  62354. //execute ready callback, if set
  62355. if (onReady) {
  62356. onReady(ground);
  62357. }
  62358. ground._setReady(true);
  62359. };
  62360. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  62361. return ground;
  62362. };
  62363. /**
  62364. * Creates a polygon mesh
  62365. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  62366. * * 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
  62367. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62368. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62369. * * 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)
  62370. * * Remember you can only change the shape positions, not their number when updating a polygon
  62371. * @param name defines the name of the mesh
  62372. * @param options defines the options used to create the mesh
  62373. * @param scene defines the hosting scene
  62374. * @returns the polygon mesh
  62375. */
  62376. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62377. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62378. var shape = options.shape;
  62379. var holes = options.holes || [];
  62380. var depth = options.depth || 0;
  62381. var contours = [];
  62382. var hole = [];
  62383. for (var i = 0; i < shape.length; i++) {
  62384. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62385. }
  62386. var epsilon = 0.00000001;
  62387. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62388. contours.pop();
  62389. }
  62390. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62391. for (var hNb = 0; hNb < holes.length; hNb++) {
  62392. hole = [];
  62393. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62394. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62395. }
  62396. polygonTriangulation.addHole(hole);
  62397. }
  62398. var polygon = polygonTriangulation.build(options.updatable, depth);
  62399. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62400. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62401. vertexData.applyToMesh(polygon, options.updatable);
  62402. return polygon;
  62403. };
  62404. ;
  62405. /**
  62406. * Creates an extruded polygon mesh, with depth in the Y direction.
  62407. * * 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)
  62408. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62409. * @param name defines the name of the mesh
  62410. * @param options defines the options used to create the mesh
  62411. * @param scene defines the hosting scene
  62412. * @returns the polygon mesh
  62413. */
  62414. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62415. return MeshBuilder.CreatePolygon(name, options, scene);
  62416. };
  62417. ;
  62418. /**
  62419. * Creates a tube mesh.
  62420. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62421. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62422. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62423. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62424. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62425. * * 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)
  62426. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62427. * * 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
  62428. * * 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
  62429. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62430. * * 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
  62431. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62432. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62433. * @param name defines the name of the mesh
  62434. * @param options defines the options used to create the mesh
  62435. * @param scene defines the hosting scene
  62436. * @returns the tube mesh
  62437. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62438. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62439. */
  62440. MeshBuilder.CreateTube = function (name, options, scene) {
  62441. var path = options.path;
  62442. var instance = options.instance;
  62443. var radius = 1.0;
  62444. if (instance) {
  62445. radius = instance.radius;
  62446. }
  62447. if (options.radius !== undefined) {
  62448. radius = options.radius;
  62449. }
  62450. ;
  62451. var tessellation = options.tessellation || 64 | 0;
  62452. var radiusFunction = options.radiusFunction || null;
  62453. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62454. var invertUV = options.invertUV || false;
  62455. var updatable = options.updatable;
  62456. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62457. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62458. // tube geometry
  62459. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62460. var tangents = path3D.getTangents();
  62461. var normals = path3D.getNormals();
  62462. var distances = path3D.getDistances();
  62463. var pi2 = Math.PI * 2;
  62464. var step = pi2 / tessellation * arc;
  62465. var returnRadius = function () { return radius; };
  62466. var radiusFunctionFinal = radiusFunction || returnRadius;
  62467. var circlePath;
  62468. var rad;
  62469. var normal;
  62470. var rotated;
  62471. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62472. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62473. for (var i = 0; i < path.length; i++) {
  62474. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62475. circlePath = Array(); // current circle array
  62476. normal = normals[i]; // current normal
  62477. for (var t = 0; t < tessellation; t++) {
  62478. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62479. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62480. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62481. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62482. circlePath[t] = rotated;
  62483. }
  62484. circlePaths[index] = circlePath;
  62485. index++;
  62486. }
  62487. // cap
  62488. var capPath = function (nbPoints, pathIndex) {
  62489. var pointCap = Array();
  62490. for (var i = 0; i < nbPoints; i++) {
  62491. pointCap.push(path[pathIndex]);
  62492. }
  62493. return pointCap;
  62494. };
  62495. switch (cap) {
  62496. case BABYLON.Mesh.NO_CAP:
  62497. break;
  62498. case BABYLON.Mesh.CAP_START:
  62499. circlePaths[0] = capPath(tessellation, 0);
  62500. circlePaths[1] = circlePaths[2].slice(0);
  62501. break;
  62502. case BABYLON.Mesh.CAP_END:
  62503. circlePaths[index] = circlePaths[index - 1].slice(0);
  62504. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62505. break;
  62506. case BABYLON.Mesh.CAP_ALL:
  62507. circlePaths[0] = capPath(tessellation, 0);
  62508. circlePaths[1] = circlePaths[2].slice(0);
  62509. circlePaths[index] = circlePaths[index - 1].slice(0);
  62510. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62511. break;
  62512. default:
  62513. break;
  62514. }
  62515. return circlePaths;
  62516. };
  62517. var path3D;
  62518. var pathArray;
  62519. if (instance) { // tube update
  62520. var arc = options.arc || instance.arc;
  62521. path3D = (instance.path3D).update(path);
  62522. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62523. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62524. instance.path3D = path3D;
  62525. instance.pathArray = pathArray;
  62526. instance.arc = arc;
  62527. instance.radius = radius;
  62528. return instance;
  62529. }
  62530. // tube creation
  62531. path3D = new BABYLON.Path3D(path);
  62532. var newPathArray = new Array();
  62533. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62534. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62535. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62536. tube.pathArray = pathArray;
  62537. tube.path3D = path3D;
  62538. tube.tessellation = tessellation;
  62539. tube.cap = cap;
  62540. tube.arc = options.arc;
  62541. tube.radius = radius;
  62542. return tube;
  62543. };
  62544. /**
  62545. * Creates a polyhedron mesh
  62546. * * 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
  62547. * * The parameter `size` (positive float, default 1) sets the polygon size
  62548. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62549. * * 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`
  62550. * * 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
  62551. * * 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)`)
  62552. * * 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
  62553. * * 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
  62554. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62555. * * 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
  62556. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62557. * @param name defines the name of the mesh
  62558. * @param options defines the options used to create the mesh
  62559. * @param scene defines the hosting scene
  62560. * @returns the polyhedron mesh
  62561. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62562. */
  62563. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62564. var polyhedron = new BABYLON.Mesh(name, scene);
  62565. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62566. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62567. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62568. vertexData.applyToMesh(polyhedron, options.updatable);
  62569. return polyhedron;
  62570. };
  62571. /**
  62572. * Creates a decal mesh.
  62573. * 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
  62574. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62575. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62576. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62577. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62578. * @param name defines the name of the mesh
  62579. * @param sourceMesh defines the mesh where the decal must be applied
  62580. * @param options defines the options used to create the mesh
  62581. * @param scene defines the hosting scene
  62582. * @returns the decal mesh
  62583. * @see http://doc.babylonjs.com/how_to/decals
  62584. */
  62585. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62586. var indices = sourceMesh.getIndices();
  62587. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62588. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62589. var position = options.position || BABYLON.Vector3.Zero();
  62590. var normal = options.normal || BABYLON.Vector3.Up();
  62591. var size = options.size || BABYLON.Vector3.One();
  62592. var angle = options.angle || 0;
  62593. // Getting correct rotation
  62594. if (!normal) {
  62595. var target = new BABYLON.Vector3(0, 0, 1);
  62596. var camera = sourceMesh.getScene().activeCamera;
  62597. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62598. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62599. }
  62600. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62601. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62602. var pitch = Math.atan2(normal.y, len);
  62603. // Matrix
  62604. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62605. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62606. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62607. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62608. var vertexData = new BABYLON.VertexData();
  62609. vertexData.indices = [];
  62610. vertexData.positions = [];
  62611. vertexData.normals = [];
  62612. vertexData.uvs = [];
  62613. var currentVertexDataIndex = 0;
  62614. var extractDecalVector3 = function (indexId) {
  62615. var result = new BABYLON.PositionNormalVertex();
  62616. if (!indices || !positions || !normals) {
  62617. return result;
  62618. }
  62619. var vertexId = indices[indexId];
  62620. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62621. // Send vector to decal local world
  62622. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62623. // Get normal
  62624. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62625. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62626. return result;
  62627. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62628. var clip = function (vertices, axis) {
  62629. if (vertices.length === 0) {
  62630. return vertices;
  62631. }
  62632. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62633. var clipVertices = function (v0, v1) {
  62634. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62635. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62636. };
  62637. var result = new Array();
  62638. for (var index = 0; index < vertices.length; index += 3) {
  62639. var v1Out;
  62640. var v2Out;
  62641. var v3Out;
  62642. var total = 0;
  62643. var nV1 = null;
  62644. var nV2 = null;
  62645. var nV3 = null;
  62646. var nV4 = null;
  62647. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62648. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62649. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62650. v1Out = d1 > 0;
  62651. v2Out = d2 > 0;
  62652. v3Out = d3 > 0;
  62653. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62654. switch (total) {
  62655. case 0:
  62656. result.push(vertices[index]);
  62657. result.push(vertices[index + 1]);
  62658. result.push(vertices[index + 2]);
  62659. break;
  62660. case 1:
  62661. if (v1Out) {
  62662. nV1 = vertices[index + 1];
  62663. nV2 = vertices[index + 2];
  62664. nV3 = clipVertices(vertices[index], nV1);
  62665. nV4 = clipVertices(vertices[index], nV2);
  62666. }
  62667. if (v2Out) {
  62668. nV1 = vertices[index];
  62669. nV2 = vertices[index + 2];
  62670. nV3 = clipVertices(vertices[index + 1], nV1);
  62671. nV4 = clipVertices(vertices[index + 1], nV2);
  62672. result.push(nV3);
  62673. result.push(nV2.clone());
  62674. result.push(nV1.clone());
  62675. result.push(nV2.clone());
  62676. result.push(nV3.clone());
  62677. result.push(nV4);
  62678. break;
  62679. }
  62680. if (v3Out) {
  62681. nV1 = vertices[index];
  62682. nV2 = vertices[index + 1];
  62683. nV3 = clipVertices(vertices[index + 2], nV1);
  62684. nV4 = clipVertices(vertices[index + 2], nV2);
  62685. }
  62686. if (nV1 && nV2 && nV3 && nV4) {
  62687. result.push(nV1.clone());
  62688. result.push(nV2.clone());
  62689. result.push(nV3);
  62690. result.push(nV4);
  62691. result.push(nV3.clone());
  62692. result.push(nV2.clone());
  62693. }
  62694. break;
  62695. case 2:
  62696. if (!v1Out) {
  62697. nV1 = vertices[index].clone();
  62698. nV2 = clipVertices(nV1, vertices[index + 1]);
  62699. nV3 = clipVertices(nV1, vertices[index + 2]);
  62700. result.push(nV1);
  62701. result.push(nV2);
  62702. result.push(nV3);
  62703. }
  62704. if (!v2Out) {
  62705. nV1 = vertices[index + 1].clone();
  62706. nV2 = clipVertices(nV1, vertices[index + 2]);
  62707. nV3 = clipVertices(nV1, vertices[index]);
  62708. result.push(nV1);
  62709. result.push(nV2);
  62710. result.push(nV3);
  62711. }
  62712. if (!v3Out) {
  62713. nV1 = vertices[index + 2].clone();
  62714. nV2 = clipVertices(nV1, vertices[index]);
  62715. nV3 = clipVertices(nV1, vertices[index + 1]);
  62716. result.push(nV1);
  62717. result.push(nV2);
  62718. result.push(nV3);
  62719. }
  62720. break;
  62721. case 3:
  62722. break;
  62723. }
  62724. }
  62725. return result;
  62726. };
  62727. for (var index = 0; index < indices.length; index += 3) {
  62728. var faceVertices = new Array();
  62729. faceVertices.push(extractDecalVector3(index));
  62730. faceVertices.push(extractDecalVector3(index + 1));
  62731. faceVertices.push(extractDecalVector3(index + 2));
  62732. // Clip
  62733. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62734. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62735. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62736. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62737. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62738. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62739. if (faceVertices.length === 0) {
  62740. continue;
  62741. }
  62742. // Add UVs and get back to world
  62743. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62744. var vertex = faceVertices[vIndex];
  62745. //TODO check for Int32Array | Uint32Array | Uint16Array
  62746. vertexData.indices.push(currentVertexDataIndex);
  62747. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62748. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62749. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62750. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62751. currentVertexDataIndex++;
  62752. }
  62753. }
  62754. // Return mesh
  62755. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62756. vertexData.applyToMesh(decal);
  62757. decal.position = position.clone();
  62758. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62759. return decal;
  62760. };
  62761. // Privates
  62762. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62763. // extrusion geometry
  62764. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62765. var tangents = path3D.getTangents();
  62766. var normals = path3D.getNormals();
  62767. var binormals = path3D.getBinormals();
  62768. var distances = path3D.getDistances();
  62769. var angle = 0;
  62770. var returnScale = function () { return scale !== null ? scale : 1; };
  62771. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62772. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62773. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62774. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62775. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62776. for (var i = 0; i < curve.length; i++) {
  62777. var shapePath = new Array();
  62778. var angleStep = rotate(i, distances[i]);
  62779. var scaleRatio = scl(i, distances[i]);
  62780. for (var p = 0; p < shape.length; p++) {
  62781. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62782. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62783. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62784. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62785. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62786. shapePath[p] = rotated;
  62787. }
  62788. shapePaths[index] = shapePath;
  62789. angle += angleStep;
  62790. index++;
  62791. }
  62792. // cap
  62793. var capPath = function (shapePath) {
  62794. var pointCap = Array();
  62795. var barycenter = BABYLON.Vector3.Zero();
  62796. var i;
  62797. for (i = 0; i < shapePath.length; i++) {
  62798. barycenter.addInPlace(shapePath[i]);
  62799. }
  62800. barycenter.scaleInPlace(1.0 / shapePath.length);
  62801. for (i = 0; i < shapePath.length; i++) {
  62802. pointCap.push(barycenter);
  62803. }
  62804. return pointCap;
  62805. };
  62806. switch (cap) {
  62807. case BABYLON.Mesh.NO_CAP:
  62808. break;
  62809. case BABYLON.Mesh.CAP_START:
  62810. shapePaths[0] = capPath(shapePaths[2]);
  62811. shapePaths[1] = shapePaths[2];
  62812. break;
  62813. case BABYLON.Mesh.CAP_END:
  62814. shapePaths[index] = shapePaths[index - 1];
  62815. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62816. break;
  62817. case BABYLON.Mesh.CAP_ALL:
  62818. shapePaths[0] = capPath(shapePaths[2]);
  62819. shapePaths[1] = shapePaths[2];
  62820. shapePaths[index] = shapePaths[index - 1];
  62821. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62822. break;
  62823. default:
  62824. break;
  62825. }
  62826. return shapePaths;
  62827. };
  62828. var path3D;
  62829. var pathArray;
  62830. if (instance) { // instance update
  62831. path3D = (instance.path3D).update(curve);
  62832. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62833. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62834. return instance;
  62835. }
  62836. // extruded shape creation
  62837. path3D = new BABYLON.Path3D(curve);
  62838. var newShapePaths = new Array();
  62839. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62840. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62841. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62842. extrudedGeneric.pathArray = pathArray;
  62843. extrudedGeneric.path3D = path3D;
  62844. extrudedGeneric.cap = cap;
  62845. return extrudedGeneric;
  62846. };
  62847. return MeshBuilder;
  62848. }());
  62849. BABYLON.MeshBuilder = MeshBuilder;
  62850. })(BABYLON || (BABYLON = {}));
  62851. //# sourceMappingURL=babylon.meshBuilder.js.map
  62852. var BABYLON;
  62853. (function (BABYLON) {
  62854. /**
  62855. * Draco compression (https://google.github.io/draco/)
  62856. *
  62857. * This class wraps the Draco module.
  62858. *
  62859. * **Encoder**
  62860. *
  62861. * The encoder is not currently implemented.
  62862. *
  62863. * **Decoder**
  62864. *
  62865. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62866. *
  62867. * To update the configuration, use the following code:
  62868. * ```javascript
  62869. * BABYLON.DracoCompression.Configuration = {
  62870. * decoder: {
  62871. * wasmUrl: "<url to the WebAssembly library>",
  62872. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62873. * fallbackUrl: "<url to the fallback JavaScript library>",
  62874. * }
  62875. * };
  62876. * ```
  62877. *
  62878. * 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.
  62879. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62880. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62881. *
  62882. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62883. * ```javascript
  62884. * var dracoCompression = new BABYLON.DracoCompression();
  62885. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62886. * [BABYLON.VertexBuffer.PositionKind]: 0
  62887. * });
  62888. * ```
  62889. *
  62890. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62891. */
  62892. var DracoCompression = /** @class */ (function () {
  62893. /**
  62894. * Constructor
  62895. */
  62896. function DracoCompression() {
  62897. }
  62898. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62899. /**
  62900. * Returns true if the decoder is available.
  62901. */
  62902. get: function () {
  62903. if (typeof DracoDecoderModule !== "undefined") {
  62904. return true;
  62905. }
  62906. var decoder = DracoCompression.Configuration.decoder;
  62907. if (decoder) {
  62908. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62909. return true;
  62910. }
  62911. if (decoder.fallbackUrl) {
  62912. return true;
  62913. }
  62914. }
  62915. return false;
  62916. },
  62917. enumerable: true,
  62918. configurable: true
  62919. });
  62920. /**
  62921. * Stop all async operations and release resources.
  62922. */
  62923. DracoCompression.prototype.dispose = function () {
  62924. };
  62925. /**
  62926. * Decode Draco compressed mesh data to vertex data.
  62927. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62928. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62929. * @returns A promise that resolves with the decoded vertex data
  62930. */
  62931. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62932. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62933. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62934. var module = wrappedModule.module;
  62935. var vertexData = new BABYLON.VertexData();
  62936. var buffer = new module.DecoderBuffer();
  62937. buffer.Init(dataView, dataView.byteLength);
  62938. var decoder = new module.Decoder();
  62939. var geometry;
  62940. var status;
  62941. try {
  62942. var type = decoder.GetEncodedGeometryType(buffer);
  62943. switch (type) {
  62944. case module.TRIANGULAR_MESH:
  62945. geometry = new module.Mesh();
  62946. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62947. break;
  62948. case module.POINT_CLOUD:
  62949. geometry = new module.PointCloud();
  62950. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62951. break;
  62952. default:
  62953. throw new Error("Invalid geometry type " + type);
  62954. }
  62955. if (!status.ok() || !geometry.ptr) {
  62956. throw new Error(status.error_msg());
  62957. }
  62958. var numPoints = geometry.num_points();
  62959. if (type === module.TRIANGULAR_MESH) {
  62960. var numFaces = geometry.num_faces();
  62961. var faceIndices = new module.DracoInt32Array();
  62962. try {
  62963. var indices = new Uint32Array(numFaces * 3);
  62964. for (var i = 0; i < numFaces; i++) {
  62965. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62966. var offset = i * 3;
  62967. indices[offset + 0] = faceIndices.GetValue(0);
  62968. indices[offset + 1] = faceIndices.GetValue(1);
  62969. indices[offset + 2] = faceIndices.GetValue(2);
  62970. }
  62971. vertexData.indices = indices;
  62972. }
  62973. finally {
  62974. module.destroy(faceIndices);
  62975. }
  62976. }
  62977. for (var kind in attributes) {
  62978. var uniqueId = attributes[kind];
  62979. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62980. var dracoData = new module.DracoFloat32Array();
  62981. try {
  62982. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62983. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62984. for (var i = 0; i < babylonData.length; i++) {
  62985. babylonData[i] = dracoData.GetValue(i);
  62986. }
  62987. vertexData.set(babylonData, kind);
  62988. }
  62989. finally {
  62990. module.destroy(dracoData);
  62991. }
  62992. }
  62993. }
  62994. finally {
  62995. if (geometry) {
  62996. module.destroy(geometry);
  62997. }
  62998. module.destroy(decoder);
  62999. module.destroy(buffer);
  63000. }
  63001. return vertexData;
  63002. });
  63003. };
  63004. DracoCompression._GetDecoderModule = function () {
  63005. if (!DracoCompression._DecoderModulePromise) {
  63006. var promise = null;
  63007. var config_1 = {};
  63008. if (typeof DracoDecoderModule !== "undefined") {
  63009. promise = Promise.resolve();
  63010. }
  63011. else {
  63012. var decoder = DracoCompression.Configuration.decoder;
  63013. if (decoder) {
  63014. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63015. promise = Promise.all([
  63016. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63017. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63018. config_1.wasmBinary = data;
  63019. })
  63020. ]);
  63021. }
  63022. else if (decoder.fallbackUrl) {
  63023. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63024. }
  63025. }
  63026. }
  63027. if (!promise) {
  63028. throw new Error("Draco decoder module is not available");
  63029. }
  63030. DracoCompression._DecoderModulePromise = promise.then(function () {
  63031. return new Promise(function (resolve) {
  63032. config_1.onModuleLoaded = function (decoderModule) {
  63033. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63034. resolve({ module: decoderModule });
  63035. };
  63036. DracoDecoderModule(config_1);
  63037. });
  63038. });
  63039. }
  63040. return DracoCompression._DecoderModulePromise;
  63041. };
  63042. DracoCompression._LoadScriptAsync = function (url) {
  63043. return new Promise(function (resolve, reject) {
  63044. BABYLON.Tools.LoadScript(url, function () {
  63045. resolve();
  63046. }, function (message) {
  63047. reject(new Error(message));
  63048. });
  63049. });
  63050. };
  63051. DracoCompression._LoadFileAsync = function (url) {
  63052. return new Promise(function (resolve, reject) {
  63053. BABYLON.Tools.LoadFile(url, function (data) {
  63054. resolve(data);
  63055. }, undefined, undefined, true, function (request, exception) {
  63056. reject(exception);
  63057. });
  63058. });
  63059. };
  63060. /**
  63061. * The configuration. Defaults to the following urls:
  63062. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63063. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63064. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63065. */
  63066. DracoCompression.Configuration = {
  63067. decoder: {
  63068. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63069. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63070. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63071. }
  63072. };
  63073. return DracoCompression;
  63074. }());
  63075. BABYLON.DracoCompression = DracoCompression;
  63076. })(BABYLON || (BABYLON = {}));
  63077. //# sourceMappingURL=babylon.dracoCompression.js.map
  63078. var BABYLON;
  63079. (function (BABYLON) {
  63080. var AudioEngine = /** @class */ (function () {
  63081. function AudioEngine() {
  63082. this._audioContext = null;
  63083. this._audioContextInitialized = false;
  63084. this.canUseWebAudio = false;
  63085. this.WarnedWebAudioUnsupported = false;
  63086. this.unlocked = false;
  63087. this.isMP3supported = false;
  63088. this.isOGGsupported = false;
  63089. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63090. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63091. this.canUseWebAudio = true;
  63092. }
  63093. var audioElem = document.createElement('audio');
  63094. try {
  63095. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63096. this.isMP3supported = true;
  63097. }
  63098. }
  63099. catch (e) {
  63100. // protect error during capability check.
  63101. }
  63102. try {
  63103. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63104. this.isOGGsupported = true;
  63105. }
  63106. }
  63107. catch (e) {
  63108. // protect error during capability check.
  63109. }
  63110. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63111. this._unlockiOSaudio();
  63112. }
  63113. else {
  63114. this.unlocked = true;
  63115. }
  63116. }
  63117. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63118. get: function () {
  63119. if (!this._audioContextInitialized) {
  63120. this._initializeAudioContext();
  63121. }
  63122. return this._audioContext;
  63123. },
  63124. enumerable: true,
  63125. configurable: true
  63126. });
  63127. AudioEngine.prototype._unlockiOSaudio = function () {
  63128. var _this = this;
  63129. var unlockaudio = function () {
  63130. if (!_this.audioContext) {
  63131. return;
  63132. }
  63133. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63134. var source = _this.audioContext.createBufferSource();
  63135. source.buffer = buffer;
  63136. source.connect(_this.audioContext.destination);
  63137. source.start(0);
  63138. setTimeout(function () {
  63139. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63140. _this.unlocked = true;
  63141. window.removeEventListener('touchend', unlockaudio, false);
  63142. if (_this.onAudioUnlocked) {
  63143. _this.onAudioUnlocked();
  63144. }
  63145. }
  63146. }, 0);
  63147. };
  63148. window.addEventListener('touchend', unlockaudio, false);
  63149. };
  63150. AudioEngine.prototype._initializeAudioContext = function () {
  63151. try {
  63152. if (this.canUseWebAudio) {
  63153. this._audioContext = new AudioContext();
  63154. // create a global volume gain node
  63155. this.masterGain = this._audioContext.createGain();
  63156. this.masterGain.gain.value = 1;
  63157. this.masterGain.connect(this._audioContext.destination);
  63158. this._audioContextInitialized = true;
  63159. }
  63160. }
  63161. catch (e) {
  63162. this.canUseWebAudio = false;
  63163. BABYLON.Tools.Error("Web Audio: " + e.message);
  63164. }
  63165. };
  63166. AudioEngine.prototype.dispose = function () {
  63167. if (this.canUseWebAudio && this._audioContextInitialized) {
  63168. if (this._connectedAnalyser && this._audioContext) {
  63169. this._connectedAnalyser.stopDebugCanvas();
  63170. this._connectedAnalyser.dispose();
  63171. this.masterGain.disconnect();
  63172. this.masterGain.connect(this._audioContext.destination);
  63173. this._connectedAnalyser = null;
  63174. }
  63175. this.masterGain.gain.value = 1;
  63176. }
  63177. this.WarnedWebAudioUnsupported = false;
  63178. };
  63179. AudioEngine.prototype.getGlobalVolume = function () {
  63180. if (this.canUseWebAudio && this._audioContextInitialized) {
  63181. return this.masterGain.gain.value;
  63182. }
  63183. else {
  63184. return -1;
  63185. }
  63186. };
  63187. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63188. if (this.canUseWebAudio && this._audioContextInitialized) {
  63189. this.masterGain.gain.value = newVolume;
  63190. }
  63191. };
  63192. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63193. if (this._connectedAnalyser) {
  63194. this._connectedAnalyser.stopDebugCanvas();
  63195. }
  63196. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63197. this._connectedAnalyser = analyser;
  63198. this.masterGain.disconnect();
  63199. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63200. }
  63201. };
  63202. return AudioEngine;
  63203. }());
  63204. BABYLON.AudioEngine = AudioEngine;
  63205. })(BABYLON || (BABYLON = {}));
  63206. //# sourceMappingURL=babylon.audioEngine.js.map
  63207. var BABYLON;
  63208. (function (BABYLON) {
  63209. var Sound = /** @class */ (function () {
  63210. /**
  63211. * Create a sound and attach it to a scene
  63212. * @param name Name of your sound
  63213. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63214. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63215. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63216. */
  63217. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63218. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63219. var _this = this;
  63220. this.autoplay = false;
  63221. this.loop = false;
  63222. this.useCustomAttenuation = false;
  63223. this.spatialSound = false;
  63224. this.refDistance = 1;
  63225. this.rolloffFactor = 1;
  63226. this.maxDistance = 100;
  63227. this.distanceModel = "linear";
  63228. this._panningModel = "equalpower";
  63229. this._playbackRate = 1;
  63230. this._streaming = false;
  63231. this._startTime = 0;
  63232. this._startOffset = 0;
  63233. this._position = BABYLON.Vector3.Zero();
  63234. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63235. this._volume = 1;
  63236. this._isReadyToPlay = false;
  63237. this.isPlaying = false;
  63238. this.isPaused = false;
  63239. this._isDirectional = false;
  63240. // Used if you'd like to create a directional sound.
  63241. // If not set, the sound will be omnidirectional
  63242. this._coneInnerAngle = 360;
  63243. this._coneOuterAngle = 360;
  63244. this._coneOuterGain = 0;
  63245. this._isOutputConnected = false;
  63246. this._urlType = "Unknown";
  63247. this.name = name;
  63248. this._scene = scene;
  63249. this._readyToPlayCallback = readyToPlayCallback;
  63250. // Default custom attenuation function is a linear attenuation
  63251. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63252. if (currentDistance < maxDistance) {
  63253. return currentVolume * (1 - currentDistance / maxDistance);
  63254. }
  63255. else {
  63256. return 0;
  63257. }
  63258. };
  63259. if (options) {
  63260. this.autoplay = options.autoplay || false;
  63261. this.loop = options.loop || false;
  63262. // if volume === 0, we need another way to check this option
  63263. if (options.volume !== undefined) {
  63264. this._volume = options.volume;
  63265. }
  63266. this.spatialSound = options.spatialSound || false;
  63267. this.maxDistance = options.maxDistance || 100;
  63268. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63269. this.rolloffFactor = options.rolloffFactor || 1;
  63270. this.refDistance = options.refDistance || 1;
  63271. this.distanceModel = options.distanceModel || "linear";
  63272. this._playbackRate = options.playbackRate || 1;
  63273. this._streaming = options.streaming || false;
  63274. }
  63275. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63276. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63277. this._soundGain.gain.value = this._volume;
  63278. this._inputAudioNode = this._soundGain;
  63279. this._ouputAudioNode = this._soundGain;
  63280. if (this.spatialSound) {
  63281. this._createSpatialParameters();
  63282. }
  63283. this._scene.mainSoundTrack.AddSound(this);
  63284. var validParameter = true;
  63285. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  63286. if (urlOrArrayBuffer) {
  63287. try {
  63288. if (typeof (urlOrArrayBuffer) === "string") {
  63289. this._urlType = "String";
  63290. }
  63291. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  63292. this._urlType = "ArrayBuffer";
  63293. }
  63294. else if (urlOrArrayBuffer instanceof MediaStream) {
  63295. this._urlType = "MediaStream";
  63296. }
  63297. else if (Array.isArray(urlOrArrayBuffer)) {
  63298. this._urlType = "Array";
  63299. }
  63300. var urls = [];
  63301. var codecSupportedFound = false;
  63302. switch (this._urlType) {
  63303. case "MediaStream":
  63304. this._streaming = true;
  63305. this._isReadyToPlay = true;
  63306. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  63307. if (this.autoplay) {
  63308. this.play();
  63309. }
  63310. if (this._readyToPlayCallback) {
  63311. this._readyToPlayCallback();
  63312. }
  63313. break;
  63314. case "ArrayBuffer":
  63315. if (urlOrArrayBuffer.byteLength > 0) {
  63316. codecSupportedFound = true;
  63317. this._soundLoaded(urlOrArrayBuffer);
  63318. }
  63319. break;
  63320. case "String":
  63321. urls.push(urlOrArrayBuffer);
  63322. case "Array":
  63323. if (urls.length === 0)
  63324. urls = urlOrArrayBuffer;
  63325. // If we found a supported format, we load it immediately and stop the loop
  63326. for (var i = 0; i < urls.length; i++) {
  63327. var url = urls[i];
  63328. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  63329. codecSupportedFound = true;
  63330. }
  63331. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  63332. codecSupportedFound = true;
  63333. }
  63334. if (url.indexOf(".wav", url.length - 4) !== -1) {
  63335. codecSupportedFound = true;
  63336. }
  63337. if (url.indexOf("blob:") !== -1) {
  63338. codecSupportedFound = true;
  63339. }
  63340. if (codecSupportedFound) {
  63341. // Loading sound using XHR2
  63342. if (!this._streaming) {
  63343. this._scene._loadFile(url, function (data) {
  63344. _this._soundLoaded(data);
  63345. }, undefined, true, true, function (exception) {
  63346. if (exception) {
  63347. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  63348. }
  63349. BABYLON.Tools.Error("Sound creation aborted.");
  63350. _this._scene.mainSoundTrack.RemoveSound(_this);
  63351. });
  63352. }
  63353. // Streaming sound using HTML5 Audio tag
  63354. else {
  63355. this._htmlAudioElement = new Audio(url);
  63356. this._htmlAudioElement.controls = false;
  63357. this._htmlAudioElement.loop = this.loop;
  63358. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  63359. this._htmlAudioElement.preload = "auto";
  63360. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  63361. _this._isReadyToPlay = true;
  63362. if (_this.autoplay) {
  63363. _this.play();
  63364. }
  63365. if (_this._readyToPlayCallback) {
  63366. _this._readyToPlayCallback();
  63367. }
  63368. });
  63369. document.body.appendChild(this._htmlAudioElement);
  63370. }
  63371. break;
  63372. }
  63373. }
  63374. break;
  63375. default:
  63376. validParameter = false;
  63377. break;
  63378. }
  63379. if (!validParameter) {
  63380. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  63381. }
  63382. else {
  63383. if (!codecSupportedFound) {
  63384. this._isReadyToPlay = true;
  63385. // Simulating a ready to play event to avoid breaking code path
  63386. if (this._readyToPlayCallback) {
  63387. window.setTimeout(function () {
  63388. if (_this._readyToPlayCallback) {
  63389. _this._readyToPlayCallback();
  63390. }
  63391. }, 1000);
  63392. }
  63393. }
  63394. }
  63395. }
  63396. catch (ex) {
  63397. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63398. this._scene.mainSoundTrack.RemoveSound(this);
  63399. }
  63400. }
  63401. }
  63402. else {
  63403. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63404. this._scene.mainSoundTrack.AddSound(this);
  63405. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63406. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63407. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63408. }
  63409. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63410. if (this._readyToPlayCallback) {
  63411. window.setTimeout(function () {
  63412. if (_this._readyToPlayCallback) {
  63413. _this._readyToPlayCallback();
  63414. }
  63415. }, 1000);
  63416. }
  63417. }
  63418. }
  63419. Sound.prototype.dispose = function () {
  63420. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63421. if (this.isPlaying) {
  63422. this.stop();
  63423. }
  63424. this._isReadyToPlay = false;
  63425. if (this.soundTrackId === -1) {
  63426. this._scene.mainSoundTrack.RemoveSound(this);
  63427. }
  63428. else {
  63429. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63430. }
  63431. if (this._soundGain) {
  63432. this._soundGain.disconnect();
  63433. this._soundGain = null;
  63434. }
  63435. if (this._soundPanner) {
  63436. this._soundPanner.disconnect();
  63437. this._soundPanner = null;
  63438. }
  63439. if (this._soundSource) {
  63440. this._soundSource.disconnect();
  63441. this._soundSource = null;
  63442. }
  63443. this._audioBuffer = null;
  63444. if (this._htmlAudioElement) {
  63445. this._htmlAudioElement.pause();
  63446. this._htmlAudioElement.src = "";
  63447. document.body.removeChild(this._htmlAudioElement);
  63448. }
  63449. if (this._streamingSource) {
  63450. this._streamingSource.disconnect();
  63451. }
  63452. if (this._connectedMesh && this._registerFunc) {
  63453. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63454. this._connectedMesh = null;
  63455. }
  63456. }
  63457. };
  63458. Sound.prototype.isReady = function () {
  63459. return this._isReadyToPlay;
  63460. };
  63461. Sound.prototype._soundLoaded = function (audioData) {
  63462. var _this = this;
  63463. if (!BABYLON.Engine.audioEngine.audioContext) {
  63464. return;
  63465. }
  63466. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63467. _this._audioBuffer = buffer;
  63468. _this._isReadyToPlay = true;
  63469. if (_this.autoplay) {
  63470. _this.play();
  63471. }
  63472. if (_this._readyToPlayCallback) {
  63473. _this._readyToPlayCallback();
  63474. }
  63475. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63476. };
  63477. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63478. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63479. this._audioBuffer = audioBuffer;
  63480. this._isReadyToPlay = true;
  63481. }
  63482. };
  63483. Sound.prototype.updateOptions = function (options) {
  63484. if (options) {
  63485. this.loop = options.loop || this.loop;
  63486. this.maxDistance = options.maxDistance || this.maxDistance;
  63487. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63488. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63489. this.refDistance = options.refDistance || this.refDistance;
  63490. this.distanceModel = options.distanceModel || this.distanceModel;
  63491. this._playbackRate = options.playbackRate || this._playbackRate;
  63492. this._updateSpatialParameters();
  63493. if (this.isPlaying) {
  63494. if (this._streaming && this._htmlAudioElement) {
  63495. this._htmlAudioElement.playbackRate = this._playbackRate;
  63496. }
  63497. else {
  63498. if (this._soundSource) {
  63499. this._soundSource.playbackRate.value = this._playbackRate;
  63500. }
  63501. }
  63502. }
  63503. }
  63504. };
  63505. Sound.prototype._createSpatialParameters = function () {
  63506. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63507. if (this._scene.headphone) {
  63508. this._panningModel = "HRTF";
  63509. }
  63510. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63511. this._updateSpatialParameters();
  63512. this._soundPanner.connect(this._ouputAudioNode);
  63513. this._inputAudioNode = this._soundPanner;
  63514. }
  63515. };
  63516. Sound.prototype._updateSpatialParameters = function () {
  63517. if (this.spatialSound && this._soundPanner) {
  63518. if (this.useCustomAttenuation) {
  63519. // Tricks to disable in a way embedded Web Audio attenuation
  63520. this._soundPanner.distanceModel = "linear";
  63521. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63522. this._soundPanner.refDistance = 1;
  63523. this._soundPanner.rolloffFactor = 1;
  63524. this._soundPanner.panningModel = this._panningModel;
  63525. }
  63526. else {
  63527. this._soundPanner.distanceModel = this.distanceModel;
  63528. this._soundPanner.maxDistance = this.maxDistance;
  63529. this._soundPanner.refDistance = this.refDistance;
  63530. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63531. this._soundPanner.panningModel = this._panningModel;
  63532. }
  63533. }
  63534. };
  63535. Sound.prototype.switchPanningModelToHRTF = function () {
  63536. this._panningModel = "HRTF";
  63537. this._switchPanningModel();
  63538. };
  63539. Sound.prototype.switchPanningModelToEqualPower = function () {
  63540. this._panningModel = "equalpower";
  63541. this._switchPanningModel();
  63542. };
  63543. Sound.prototype._switchPanningModel = function () {
  63544. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63545. this._soundPanner.panningModel = this._panningModel;
  63546. }
  63547. };
  63548. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63550. if (this._isOutputConnected) {
  63551. this._ouputAudioNode.disconnect();
  63552. }
  63553. this._ouputAudioNode.connect(soundTrackAudioNode);
  63554. this._isOutputConnected = true;
  63555. }
  63556. };
  63557. /**
  63558. * Transform this sound into a directional source
  63559. * @param coneInnerAngle Size of the inner cone in degree
  63560. * @param coneOuterAngle Size of the outer cone in degree
  63561. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63562. */
  63563. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63564. if (coneOuterAngle < coneInnerAngle) {
  63565. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63566. return;
  63567. }
  63568. this._coneInnerAngle = coneInnerAngle;
  63569. this._coneOuterAngle = coneOuterAngle;
  63570. this._coneOuterGain = coneOuterGain;
  63571. this._isDirectional = true;
  63572. if (this.isPlaying && this.loop) {
  63573. this.stop();
  63574. this.play();
  63575. }
  63576. };
  63577. Sound.prototype.setPosition = function (newPosition) {
  63578. this._position = newPosition;
  63579. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63580. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63581. }
  63582. };
  63583. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63584. this._localDirection = newLocalDirection;
  63585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63586. this._updateDirection();
  63587. }
  63588. };
  63589. Sound.prototype._updateDirection = function () {
  63590. if (!this._connectedMesh || !this._soundPanner) {
  63591. return;
  63592. }
  63593. var mat = this._connectedMesh.getWorldMatrix();
  63594. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63595. direction.normalize();
  63596. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63597. };
  63598. Sound.prototype.updateDistanceFromListener = function () {
  63599. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63600. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63601. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63602. }
  63603. };
  63604. Sound.prototype.setAttenuationFunction = function (callback) {
  63605. this._customAttenuationFunction = callback;
  63606. };
  63607. /**
  63608. * Play the sound
  63609. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63610. * @param offset (optional) Start the sound setting it at a specific time
  63611. */
  63612. Sound.prototype.play = function (time, offset) {
  63613. var _this = this;
  63614. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63615. try {
  63616. if (this._startOffset < 0) {
  63617. time = -this._startOffset;
  63618. this._startOffset = 0;
  63619. }
  63620. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63621. if (!this._soundSource || !this._streamingSource) {
  63622. if (this.spatialSound && this._soundPanner) {
  63623. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63624. if (this._isDirectional) {
  63625. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63626. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63627. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63628. if (this._connectedMesh) {
  63629. this._updateDirection();
  63630. }
  63631. else {
  63632. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63633. }
  63634. }
  63635. }
  63636. }
  63637. if (this._streaming) {
  63638. if (!this._streamingSource) {
  63639. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63640. this._htmlAudioElement.onended = function () { _this._onended(); };
  63641. this._htmlAudioElement.playbackRate = this._playbackRate;
  63642. }
  63643. this._streamingSource.disconnect();
  63644. this._streamingSource.connect(this._inputAudioNode);
  63645. if (this._htmlAudioElement) {
  63646. this._htmlAudioElement.play();
  63647. }
  63648. }
  63649. else {
  63650. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63651. this._soundSource.buffer = this._audioBuffer;
  63652. this._soundSource.connect(this._inputAudioNode);
  63653. this._soundSource.loop = this.loop;
  63654. this._soundSource.playbackRate.value = this._playbackRate;
  63655. this._soundSource.onended = function () { _this._onended(); };
  63656. if (this._soundSource.buffer) {
  63657. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63658. }
  63659. }
  63660. this._startTime = startTime;
  63661. this.isPlaying = true;
  63662. this.isPaused = false;
  63663. }
  63664. catch (ex) {
  63665. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63666. }
  63667. }
  63668. };
  63669. Sound.prototype._onended = function () {
  63670. this.isPlaying = false;
  63671. if (this.onended) {
  63672. this.onended();
  63673. }
  63674. };
  63675. /**
  63676. * Stop the sound
  63677. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63678. */
  63679. Sound.prototype.stop = function (time) {
  63680. if (this.isPlaying) {
  63681. if (this._streaming) {
  63682. if (this._htmlAudioElement) {
  63683. this._htmlAudioElement.pause();
  63684. // Test needed for Firefox or it will generate an Invalid State Error
  63685. if (this._htmlAudioElement.currentTime > 0) {
  63686. this._htmlAudioElement.currentTime = 0;
  63687. }
  63688. }
  63689. else {
  63690. this._streamingSource.disconnect();
  63691. }
  63692. }
  63693. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63694. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63695. this._soundSource.stop(stopTime);
  63696. this._soundSource.onended = function () { };
  63697. if (!this.isPaused) {
  63698. this._startOffset = 0;
  63699. }
  63700. }
  63701. this.isPlaying = false;
  63702. }
  63703. };
  63704. Sound.prototype.pause = function () {
  63705. if (this.isPlaying) {
  63706. this.isPaused = true;
  63707. if (this._streaming) {
  63708. if (this._htmlAudioElement) {
  63709. this._htmlAudioElement.pause();
  63710. }
  63711. else {
  63712. this._streamingSource.disconnect();
  63713. }
  63714. }
  63715. else if (BABYLON.Engine.audioEngine.audioContext) {
  63716. this.stop(0);
  63717. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63718. }
  63719. }
  63720. };
  63721. Sound.prototype.setVolume = function (newVolume, time) {
  63722. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63723. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63724. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63725. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63726. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63727. }
  63728. else {
  63729. this._soundGain.gain.value = newVolume;
  63730. }
  63731. }
  63732. this._volume = newVolume;
  63733. };
  63734. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63735. this._playbackRate = newPlaybackRate;
  63736. if (this.isPlaying) {
  63737. if (this._streaming && this._htmlAudioElement) {
  63738. this._htmlAudioElement.playbackRate = this._playbackRate;
  63739. }
  63740. else if (this._soundSource) {
  63741. this._soundSource.playbackRate.value = this._playbackRate;
  63742. }
  63743. }
  63744. };
  63745. Sound.prototype.getVolume = function () {
  63746. return this._volume;
  63747. };
  63748. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63749. var _this = this;
  63750. if (this._connectedMesh && this._registerFunc) {
  63751. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63752. this._registerFunc = null;
  63753. }
  63754. this._connectedMesh = meshToConnectTo;
  63755. if (!this.spatialSound) {
  63756. this.spatialSound = true;
  63757. this._createSpatialParameters();
  63758. if (this.isPlaying && this.loop) {
  63759. this.stop();
  63760. this.play();
  63761. }
  63762. }
  63763. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63764. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63765. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63766. };
  63767. Sound.prototype.detachFromMesh = function () {
  63768. if (this._connectedMesh && this._registerFunc) {
  63769. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63770. this._registerFunc = null;
  63771. this._connectedMesh = null;
  63772. }
  63773. };
  63774. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63775. if (!node.getBoundingInfo) {
  63776. return;
  63777. }
  63778. var mesh = node;
  63779. var boundingInfo = mesh.getBoundingInfo();
  63780. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63781. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63782. this._updateDirection();
  63783. }
  63784. };
  63785. Sound.prototype.clone = function () {
  63786. var _this = this;
  63787. if (!this._streaming) {
  63788. var setBufferAndRun = function () {
  63789. if (_this._isReadyToPlay) {
  63790. clonedSound._audioBuffer = _this.getAudioBuffer();
  63791. clonedSound._isReadyToPlay = true;
  63792. if (clonedSound.autoplay) {
  63793. clonedSound.play();
  63794. }
  63795. }
  63796. else {
  63797. window.setTimeout(setBufferAndRun, 300);
  63798. }
  63799. };
  63800. var currentOptions = {
  63801. autoplay: this.autoplay, loop: this.loop,
  63802. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63803. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63804. refDistance: this.refDistance, distanceModel: this.distanceModel
  63805. };
  63806. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63807. if (this.useCustomAttenuation) {
  63808. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63809. }
  63810. clonedSound.setPosition(this._position);
  63811. clonedSound.setPlaybackRate(this._playbackRate);
  63812. setBufferAndRun();
  63813. return clonedSound;
  63814. }
  63815. // Can't clone a streaming sound
  63816. else {
  63817. return null;
  63818. }
  63819. };
  63820. Sound.prototype.getAudioBuffer = function () {
  63821. return this._audioBuffer;
  63822. };
  63823. Sound.prototype.serialize = function () {
  63824. var serializationObject = {
  63825. name: this.name,
  63826. url: this.name,
  63827. autoplay: this.autoplay,
  63828. loop: this.loop,
  63829. volume: this._volume,
  63830. spatialSound: this.spatialSound,
  63831. maxDistance: this.maxDistance,
  63832. rolloffFactor: this.rolloffFactor,
  63833. refDistance: this.refDistance,
  63834. distanceModel: this.distanceModel,
  63835. playbackRate: this._playbackRate,
  63836. panningModel: this._panningModel,
  63837. soundTrackId: this.soundTrackId
  63838. };
  63839. if (this.spatialSound) {
  63840. if (this._connectedMesh)
  63841. serializationObject.connectedMeshId = this._connectedMesh.id;
  63842. serializationObject.position = this._position.asArray();
  63843. serializationObject.refDistance = this.refDistance;
  63844. serializationObject.distanceModel = this.distanceModel;
  63845. serializationObject.isDirectional = this._isDirectional;
  63846. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63847. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63848. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63849. serializationObject.coneOuterGain = this._coneOuterGain;
  63850. }
  63851. return serializationObject;
  63852. };
  63853. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63854. var soundName = parsedSound.name;
  63855. var soundUrl;
  63856. if (parsedSound.url) {
  63857. soundUrl = rootUrl + parsedSound.url;
  63858. }
  63859. else {
  63860. soundUrl = rootUrl + soundName;
  63861. }
  63862. var options = {
  63863. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63864. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63865. rolloffFactor: parsedSound.rolloffFactor,
  63866. refDistance: parsedSound.refDistance,
  63867. distanceModel: parsedSound.distanceModel,
  63868. playbackRate: parsedSound.playbackRate
  63869. };
  63870. var newSound;
  63871. if (!sourceSound) {
  63872. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63873. scene._addPendingData(newSound);
  63874. }
  63875. else {
  63876. var setBufferAndRun = function () {
  63877. if (sourceSound._isReadyToPlay) {
  63878. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63879. newSound._isReadyToPlay = true;
  63880. if (newSound.autoplay) {
  63881. newSound.play();
  63882. }
  63883. }
  63884. else {
  63885. window.setTimeout(setBufferAndRun, 300);
  63886. }
  63887. };
  63888. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63889. setBufferAndRun();
  63890. }
  63891. if (parsedSound.position) {
  63892. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63893. newSound.setPosition(soundPosition);
  63894. }
  63895. if (parsedSound.isDirectional) {
  63896. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63897. if (parsedSound.localDirectionToMesh) {
  63898. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63899. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63900. }
  63901. }
  63902. if (parsedSound.connectedMeshId) {
  63903. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63904. if (connectedMesh) {
  63905. newSound.attachToMesh(connectedMesh);
  63906. }
  63907. }
  63908. return newSound;
  63909. };
  63910. return Sound;
  63911. }());
  63912. BABYLON.Sound = Sound;
  63913. })(BABYLON || (BABYLON = {}));
  63914. //# sourceMappingURL=babylon.sound.js.map
  63915. var BABYLON;
  63916. (function (BABYLON) {
  63917. var SoundTrack = /** @class */ (function () {
  63918. function SoundTrack(scene, options) {
  63919. this.id = -1;
  63920. this._isMainTrack = false;
  63921. this._isInitialized = false;
  63922. this._scene = scene;
  63923. this.soundCollection = new Array();
  63924. this._options = options;
  63925. if (!this._isMainTrack) {
  63926. this._scene.soundTracks.push(this);
  63927. this.id = this._scene.soundTracks.length - 1;
  63928. }
  63929. }
  63930. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63931. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63932. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63933. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63934. if (this._options) {
  63935. if (this._options.volume) {
  63936. this._outputAudioNode.gain.value = this._options.volume;
  63937. }
  63938. if (this._options.mainTrack) {
  63939. this._isMainTrack = this._options.mainTrack;
  63940. }
  63941. }
  63942. this._isInitialized = true;
  63943. }
  63944. };
  63945. SoundTrack.prototype.dispose = function () {
  63946. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63947. if (this._connectedAnalyser) {
  63948. this._connectedAnalyser.stopDebugCanvas();
  63949. }
  63950. while (this.soundCollection.length) {
  63951. this.soundCollection[0].dispose();
  63952. }
  63953. if (this._outputAudioNode) {
  63954. this._outputAudioNode.disconnect();
  63955. }
  63956. this._outputAudioNode = null;
  63957. }
  63958. };
  63959. SoundTrack.prototype.AddSound = function (sound) {
  63960. if (!this._isInitialized) {
  63961. this._initializeSoundTrackAudioGraph();
  63962. }
  63963. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63964. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63965. }
  63966. if (sound.soundTrackId) {
  63967. if (sound.soundTrackId === -1) {
  63968. this._scene.mainSoundTrack.RemoveSound(sound);
  63969. }
  63970. else {
  63971. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63972. }
  63973. }
  63974. this.soundCollection.push(sound);
  63975. sound.soundTrackId = this.id;
  63976. };
  63977. SoundTrack.prototype.RemoveSound = function (sound) {
  63978. var index = this.soundCollection.indexOf(sound);
  63979. if (index !== -1) {
  63980. this.soundCollection.splice(index, 1);
  63981. }
  63982. };
  63983. SoundTrack.prototype.setVolume = function (newVolume) {
  63984. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63985. this._outputAudioNode.gain.value = newVolume;
  63986. }
  63987. };
  63988. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63989. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63990. for (var i = 0; i < this.soundCollection.length; i++) {
  63991. this.soundCollection[i].switchPanningModelToHRTF();
  63992. }
  63993. }
  63994. };
  63995. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63996. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63997. for (var i = 0; i < this.soundCollection.length; i++) {
  63998. this.soundCollection[i].switchPanningModelToEqualPower();
  63999. }
  64000. }
  64001. };
  64002. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64003. if (this._connectedAnalyser) {
  64004. this._connectedAnalyser.stopDebugCanvas();
  64005. }
  64006. this._connectedAnalyser = analyser;
  64007. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64008. this._outputAudioNode.disconnect();
  64009. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64010. }
  64011. };
  64012. return SoundTrack;
  64013. }());
  64014. BABYLON.SoundTrack = SoundTrack;
  64015. })(BABYLON || (BABYLON = {}));
  64016. //# sourceMappingURL=babylon.soundtrack.js.map
  64017. var BABYLON;
  64018. (function (BABYLON) {
  64019. /**
  64020. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64021. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64022. */
  64023. var Analyser = /** @class */ (function () {
  64024. /**
  64025. * Creates a new analyser
  64026. * @param scene defines hosting scene
  64027. */
  64028. function Analyser(scene) {
  64029. /**
  64030. * Gets or sets the smoothing
  64031. * @ignorenaming
  64032. */
  64033. this.SMOOTHING = 0.75;
  64034. /**
  64035. * Gets or sets the FFT table size
  64036. * @ignorenaming
  64037. */
  64038. this.FFT_SIZE = 512;
  64039. /**
  64040. * Gets or sets the bar graph amplitude
  64041. * @ignorenaming
  64042. */
  64043. this.BARGRAPHAMPLITUDE = 256;
  64044. /**
  64045. * Gets or sets the position of the debug canvas
  64046. * @ignorenaming
  64047. */
  64048. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64049. /**
  64050. * Gets or sets the debug canvas size
  64051. * @ignorenaming
  64052. */
  64053. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64054. this._scene = scene;
  64055. this._audioEngine = BABYLON.Engine.audioEngine;
  64056. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64057. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64058. this._webAudioAnalyser.minDecibels = -140;
  64059. this._webAudioAnalyser.maxDecibels = 0;
  64060. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64061. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64062. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64063. }
  64064. }
  64065. /**
  64066. * Get the number of data values you will have to play with for the visualization
  64067. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64068. * @returns a number
  64069. */
  64070. Analyser.prototype.getFrequencyBinCount = function () {
  64071. if (this._audioEngine.canUseWebAudio) {
  64072. return this._webAudioAnalyser.frequencyBinCount;
  64073. }
  64074. else {
  64075. return 0;
  64076. }
  64077. };
  64078. /**
  64079. * Gets the current frequency data as a byte array
  64080. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64081. * @returns a Uint8Array
  64082. */
  64083. Analyser.prototype.getByteFrequencyData = function () {
  64084. if (this._audioEngine.canUseWebAudio) {
  64085. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64086. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64087. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64088. }
  64089. return this._byteFreqs;
  64090. };
  64091. /**
  64092. * Gets the current waveform as a byte array
  64093. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64094. * @returns a Uint8Array
  64095. */
  64096. Analyser.prototype.getByteTimeDomainData = function () {
  64097. if (this._audioEngine.canUseWebAudio) {
  64098. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64099. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64100. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64101. }
  64102. return this._byteTime;
  64103. };
  64104. /**
  64105. * Gets the current frequency data as a float array
  64106. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64107. * @returns a Float32Array
  64108. */
  64109. Analyser.prototype.getFloatFrequencyData = function () {
  64110. if (this._audioEngine.canUseWebAudio) {
  64111. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64112. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64113. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64114. }
  64115. return this._floatFreqs;
  64116. };
  64117. /**
  64118. * Renders the debug canvas
  64119. */
  64120. Analyser.prototype.drawDebugCanvas = function () {
  64121. var _this = this;
  64122. if (this._audioEngine.canUseWebAudio) {
  64123. if (!this._debugCanvas) {
  64124. this._debugCanvas = document.createElement("canvas");
  64125. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64126. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64127. this._debugCanvas.style.position = "absolute";
  64128. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64129. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64130. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64131. document.body.appendChild(this._debugCanvas);
  64132. this._registerFunc = function () {
  64133. _this.drawDebugCanvas();
  64134. };
  64135. this._scene.registerBeforeRender(this._registerFunc);
  64136. }
  64137. if (this._registerFunc && this._debugCanvasContext) {
  64138. var workingArray = this.getByteFrequencyData();
  64139. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64140. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64141. // Draw the frequency domain chart.
  64142. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64143. var value = workingArray[i];
  64144. var percent = value / this.BARGRAPHAMPLITUDE;
  64145. var height = this.DEBUGCANVASSIZE.height * percent;
  64146. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64147. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64148. var hue = i / this.getFrequencyBinCount() * 360;
  64149. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64150. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64151. }
  64152. }
  64153. }
  64154. };
  64155. /**
  64156. * Stops rendering the debug canvas and removes it
  64157. */
  64158. Analyser.prototype.stopDebugCanvas = function () {
  64159. if (this._debugCanvas) {
  64160. if (this._registerFunc) {
  64161. this._scene.unregisterBeforeRender(this._registerFunc);
  64162. this._registerFunc = null;
  64163. }
  64164. document.body.removeChild(this._debugCanvas);
  64165. this._debugCanvas = null;
  64166. this._debugCanvasContext = null;
  64167. }
  64168. };
  64169. /**
  64170. * Connects two audio nodes
  64171. * @param inputAudioNode defines first node to connect
  64172. * @param outputAudioNode defines second node to connect
  64173. */
  64174. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64175. if (this._audioEngine.canUseWebAudio) {
  64176. inputAudioNode.connect(this._webAudioAnalyser);
  64177. this._webAudioAnalyser.connect(outputAudioNode);
  64178. }
  64179. };
  64180. /**
  64181. * Releases all associated resources
  64182. */
  64183. Analyser.prototype.dispose = function () {
  64184. if (this._audioEngine.canUseWebAudio) {
  64185. this._webAudioAnalyser.disconnect();
  64186. }
  64187. };
  64188. return Analyser;
  64189. }());
  64190. BABYLON.Analyser = Analyser;
  64191. })(BABYLON || (BABYLON = {}));
  64192. //# sourceMappingURL=babylon.analyser.js.map
  64193. var BABYLON;
  64194. (function (BABYLON) {
  64195. var CubeTexture = /** @class */ (function (_super) {
  64196. __extends(CubeTexture, _super);
  64197. /**
  64198. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  64199. * as prefiltered data.
  64200. * @param rootUrl defines the url of the texture or the root name of the six images
  64201. * @param scene defines the scene the texture is attached to
  64202. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  64203. * @param noMipmap defines if mipmaps should be created or not
  64204. * @param files defines the six files to load for the different faces
  64205. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  64206. * @param onError defines a callback triggered in case of error during load
  64207. * @param format defines the internal format to use for the texture once loaded
  64208. * @param prefiltered defines whether or not the texture is created from prefiltered data
  64209. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  64210. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64211. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64212. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64213. * @return the cube texture
  64214. */
  64215. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  64216. if (extensions === void 0) { extensions = null; }
  64217. if (noMipmap === void 0) { noMipmap = false; }
  64218. if (files === void 0) { files = null; }
  64219. if (onLoad === void 0) { onLoad = null; }
  64220. if (onError === void 0) { onError = null; }
  64221. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64222. if (prefiltered === void 0) { prefiltered = false; }
  64223. if (forcedExtension === void 0) { forcedExtension = null; }
  64224. if (createPolynomials === void 0) { createPolynomials = false; }
  64225. if (lodScale === void 0) { lodScale = 0.8; }
  64226. if (lodOffset === void 0) { lodOffset = 0; }
  64227. var _this = _super.call(this, scene) || this;
  64228. /**
  64229. * Gets or sets the center of the bounding box associated with the cube texture
  64230. * It must define where the camera used to render the texture was set
  64231. */
  64232. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64233. _this._rotationY = 0;
  64234. /** @hidden */
  64235. _this._prefiltered = false;
  64236. _this.name = rootUrl;
  64237. _this.url = rootUrl;
  64238. _this._noMipmap = noMipmap;
  64239. _this.hasAlpha = false;
  64240. _this._format = format;
  64241. _this.isCube = true;
  64242. _this._textureMatrix = BABYLON.Matrix.Identity();
  64243. _this._createPolynomials = createPolynomials;
  64244. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64245. if (!rootUrl && !files) {
  64246. return _this;
  64247. }
  64248. var lastDot = rootUrl.lastIndexOf(".");
  64249. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  64250. var isDDS = (extension === ".dds");
  64251. var isEnv = (extension === ".env");
  64252. if (isEnv) {
  64253. _this.gammaSpace = false;
  64254. _this._prefiltered = false;
  64255. }
  64256. else {
  64257. _this._prefiltered = prefiltered;
  64258. if (prefiltered) {
  64259. _this.gammaSpace = false;
  64260. }
  64261. }
  64262. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  64263. if (!files) {
  64264. if (!isEnv && !isDDS && !extensions) {
  64265. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  64266. }
  64267. files = [];
  64268. if (extensions) {
  64269. for (var index = 0; index < extensions.length; index++) {
  64270. files.push(rootUrl + extensions[index]);
  64271. }
  64272. }
  64273. }
  64274. _this._files = files;
  64275. if (!_this._texture) {
  64276. if (!scene.useDelayedTextureLoading) {
  64277. if (prefiltered) {
  64278. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  64279. }
  64280. else {
  64281. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  64282. }
  64283. }
  64284. else {
  64285. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64286. }
  64287. }
  64288. else if (onLoad) {
  64289. if (_this._texture.isReady) {
  64290. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  64291. }
  64292. else {
  64293. _this._texture.onLoadedObservable.add(onLoad);
  64294. }
  64295. }
  64296. return _this;
  64297. }
  64298. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  64299. get: function () {
  64300. return this._boundingBoxSize;
  64301. },
  64302. /**
  64303. * Gets or sets the size of the bounding box associated with the cube texture
  64304. * When defined, the cubemap will switch to local mode
  64305. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64306. * @example https://www.babylonjs-playground.com/#RNASML
  64307. */
  64308. set: function (value) {
  64309. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64310. return;
  64311. }
  64312. this._boundingBoxSize = value;
  64313. var scene = this.getScene();
  64314. if (scene) {
  64315. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64316. }
  64317. },
  64318. enumerable: true,
  64319. configurable: true
  64320. });
  64321. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  64322. /**
  64323. * Gets texture matrix rotation angle around Y axis radians.
  64324. */
  64325. get: function () {
  64326. return this._rotationY;
  64327. },
  64328. /**
  64329. * Sets texture matrix rotation angle around Y axis in radians.
  64330. */
  64331. set: function (value) {
  64332. this._rotationY = value;
  64333. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  64334. },
  64335. enumerable: true,
  64336. configurable: true
  64337. });
  64338. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  64339. var rootUrlKey = "";
  64340. files.forEach(function (url) { return rootUrlKey += url; });
  64341. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  64342. };
  64343. /**
  64344. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  64345. * @param url defines the url of the prefiltered texture
  64346. * @param scene defines the scene the texture is attached to
  64347. * @param forcedExtension defines the extension of the file if different from the url
  64348. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64349. * @return the prefiltered texture
  64350. */
  64351. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  64352. if (forcedExtension === void 0) { forcedExtension = null; }
  64353. if (createPolynomials === void 0) { createPolynomials = true; }
  64354. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  64355. };
  64356. // Methods
  64357. CubeTexture.prototype.delayLoad = function () {
  64358. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64359. return;
  64360. }
  64361. var scene = this.getScene();
  64362. if (!scene) {
  64363. return;
  64364. }
  64365. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64366. this._texture = this._getFromCache(this.url, this._noMipmap);
  64367. if (!this._texture) {
  64368. if (this._prefiltered) {
  64369. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  64370. }
  64371. else {
  64372. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  64373. }
  64374. }
  64375. };
  64376. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  64377. return this._textureMatrix;
  64378. };
  64379. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64380. this._textureMatrix = value;
  64381. };
  64382. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64383. var texture = BABYLON.SerializationHelper.Parse(function () {
  64384. var prefiltered = false;
  64385. if (parsedTexture.prefiltered) {
  64386. prefiltered = parsedTexture.prefiltered;
  64387. }
  64388. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  64389. }, parsedTexture, scene);
  64390. // Local Cubemaps
  64391. if (parsedTexture.boundingBoxPosition) {
  64392. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  64393. }
  64394. if (parsedTexture.boundingBoxSize) {
  64395. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  64396. }
  64397. // Animations
  64398. if (parsedTexture.animations) {
  64399. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  64400. var parsedAnimation = parsedTexture.animations[animationIndex];
  64401. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  64402. }
  64403. }
  64404. return texture;
  64405. };
  64406. CubeTexture.prototype.clone = function () {
  64407. var _this = this;
  64408. return BABYLON.SerializationHelper.Clone(function () {
  64409. var scene = _this.getScene();
  64410. if (!scene) {
  64411. return _this;
  64412. }
  64413. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64414. }, this);
  64415. };
  64416. __decorate([
  64417. BABYLON.serialize("rotationY")
  64418. ], CubeTexture.prototype, "_rotationY", void 0);
  64419. return CubeTexture;
  64420. }(BABYLON.BaseTexture));
  64421. BABYLON.CubeTexture = CubeTexture;
  64422. })(BABYLON || (BABYLON = {}));
  64423. //# sourceMappingURL=babylon.cubeTexture.js.map
  64424. var BABYLON;
  64425. (function (BABYLON) {
  64426. /**
  64427. * Raw cube texture where the raw buffers are passed in
  64428. */
  64429. var RawCubeTexture = /** @class */ (function (_super) {
  64430. __extends(RawCubeTexture, _super);
  64431. /**
  64432. * Creates a cube texture where the raw buffers are passed in.
  64433. * @param scene defines the scene the texture is attached to
  64434. * @param data defines the array of data to use to create each face
  64435. * @param size defines the size of the textures
  64436. * @param format defines the format of the data
  64437. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  64438. * @param generateMipMaps defines if the engine should generate the mip levels
  64439. * @param invertY defines if data must be stored with Y axis inverted
  64440. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  64441. * @param compression defines the compression used (null by default)
  64442. */
  64443. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  64444. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64445. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64446. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64447. if (invertY === void 0) { invertY = false; }
  64448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64449. if (compression === void 0) { compression = null; }
  64450. var _this = _super.call(this, "", scene) || this;
  64451. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  64452. return _this;
  64453. }
  64454. /**
  64455. * Updates the raw cube texture.
  64456. * @param data defines the data to store
  64457. * @param format defines the data format
  64458. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  64459. * @param invertY defines if data must be stored with Y axis inverted
  64460. * @param compression defines the compression used (null by default)
  64461. * @param level defines which level of the texture to update
  64462. */
  64463. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  64464. if (compression === void 0) { compression = null; }
  64465. if (level === void 0) { level = 0; }
  64466. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  64467. };
  64468. /**
  64469. * Updates a raw cube texture with RGBD encoded data.
  64470. * @param data defines the array of data [mipmap][face] to use to create each face
  64471. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  64472. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64473. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64474. * @returns a promsie that resolves when the operation is complete
  64475. */
  64476. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  64477. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  64478. if (lodScale === void 0) { lodScale = 0.8; }
  64479. if (lodOffset === void 0) { lodOffset = 0; }
  64480. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  64481. };
  64482. /**
  64483. * Clones the raw cube texture.
  64484. * @return a new cube texture
  64485. */
  64486. RawCubeTexture.prototype.clone = function () {
  64487. var _this = this;
  64488. return BABYLON.SerializationHelper.Clone(function () {
  64489. var scene = _this.getScene();
  64490. var internalTexture = _this._texture;
  64491. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  64492. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  64493. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  64494. }
  64495. return texture;
  64496. }, this);
  64497. };
  64498. /** @hidden */
  64499. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  64500. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  64501. internalTexture._bufferViewArrayArray = data;
  64502. internalTexture._lodGenerationScale = lodScale;
  64503. internalTexture._lodGenerationOffset = lodOffset;
  64504. internalTexture._sphericalPolynomial = sphericalPolynomial;
  64505. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  64506. internalTexture.isReady = true;
  64507. });
  64508. };
  64509. return RawCubeTexture;
  64510. }(BABYLON.CubeTexture));
  64511. BABYLON.RawCubeTexture = RawCubeTexture;
  64512. })(BABYLON || (BABYLON = {}));
  64513. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  64514. var BABYLON;
  64515. (function (BABYLON) {
  64516. var RenderTargetTexture = /** @class */ (function (_super) {
  64517. __extends(RenderTargetTexture, _super);
  64518. /**
  64519. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  64520. * or used a shadow, depth texture...
  64521. * @param name The friendly name of the texture
  64522. * @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)
  64523. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  64524. * @param generateMipMaps True if mip maps need to be generated after render.
  64525. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  64526. * @param type The type of the buffer in the RTT (int, half float, float...)
  64527. * @param isCube True if a cube texture needs to be created
  64528. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  64529. * @param generateDepthBuffer True to generate a depth buffer
  64530. * @param generateStencilBuffer True to generate a stencil buffer
  64531. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  64532. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  64533. */
  64534. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  64535. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  64536. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64537. if (isCube === void 0) { isCube = false; }
  64538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64539. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64540. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  64541. if (isMulti === void 0) { isMulti = false; }
  64542. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64543. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64544. _this.isCube = isCube;
  64545. /**
  64546. * Use this list to define the list of mesh you want to render.
  64547. */
  64548. _this.renderList = new Array();
  64549. _this.renderParticles = true;
  64550. _this.renderSprites = false;
  64551. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  64552. _this.ignoreCameraViewport = false;
  64553. // Events
  64554. /**
  64555. * An event triggered when the texture is unbind.
  64556. */
  64557. _this.onBeforeBindObservable = new BABYLON.Observable();
  64558. /**
  64559. * An event triggered when the texture is unbind.
  64560. */
  64561. _this.onAfterUnbindObservable = new BABYLON.Observable();
  64562. /**
  64563. * An event triggered before rendering the texture
  64564. */
  64565. _this.onBeforeRenderObservable = new BABYLON.Observable();
  64566. /**
  64567. * An event triggered after rendering the texture
  64568. */
  64569. _this.onAfterRenderObservable = new BABYLON.Observable();
  64570. /**
  64571. * An event triggered after the texture clear
  64572. */
  64573. _this.onClearObservable = new BABYLON.Observable();
  64574. _this._currentRefreshId = -1;
  64575. _this._refreshRate = 1;
  64576. _this._samples = 1;
  64577. /**
  64578. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  64579. * It must define where the camera used to render the texture is set
  64580. */
  64581. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64582. scene = _this.getScene();
  64583. if (!scene) {
  64584. return _this;
  64585. }
  64586. _this._engine = scene.getEngine();
  64587. _this.name = name;
  64588. _this.isRenderTarget = true;
  64589. _this._initialSizeParameter = size;
  64590. _this._processSizeParameter(size);
  64591. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  64592. });
  64593. _this._generateMipMaps = generateMipMaps ? true : false;
  64594. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  64595. // Rendering groups
  64596. _this._renderingManager = new BABYLON.RenderingManager(scene);
  64597. if (isMulti) {
  64598. return _this;
  64599. }
  64600. _this._renderTargetOptions = {
  64601. generateMipMaps: generateMipMaps,
  64602. type: type,
  64603. format: format,
  64604. samplingMode: samplingMode,
  64605. generateDepthBuffer: generateDepthBuffer,
  64606. generateStencilBuffer: generateStencilBuffer
  64607. };
  64608. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  64609. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64610. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64611. }
  64612. if (isCube) {
  64613. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  64614. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  64615. _this._textureMatrix = BABYLON.Matrix.Identity();
  64616. }
  64617. else {
  64618. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  64619. }
  64620. return _this;
  64621. }
  64622. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  64623. get: function () {
  64624. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  64625. },
  64626. enumerable: true,
  64627. configurable: true
  64628. });
  64629. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  64630. get: function () {
  64631. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  64632. },
  64633. enumerable: true,
  64634. configurable: true
  64635. });
  64636. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  64637. get: function () {
  64638. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  64639. },
  64640. enumerable: true,
  64641. configurable: true
  64642. });
  64643. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  64644. set: function (callback) {
  64645. if (this._onAfterUnbindObserver) {
  64646. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  64647. }
  64648. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  64649. },
  64650. enumerable: true,
  64651. configurable: true
  64652. });
  64653. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  64654. set: function (callback) {
  64655. if (this._onBeforeRenderObserver) {
  64656. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64657. }
  64658. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64659. },
  64660. enumerable: true,
  64661. configurable: true
  64662. });
  64663. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64664. set: function (callback) {
  64665. if (this._onAfterRenderObserver) {
  64666. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64667. }
  64668. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64669. },
  64670. enumerable: true,
  64671. configurable: true
  64672. });
  64673. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64674. set: function (callback) {
  64675. if (this._onClearObserver) {
  64676. this.onClearObservable.remove(this._onClearObserver);
  64677. }
  64678. this._onClearObserver = this.onClearObservable.add(callback);
  64679. },
  64680. enumerable: true,
  64681. configurable: true
  64682. });
  64683. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64684. get: function () {
  64685. return this._renderTargetOptions;
  64686. },
  64687. enumerable: true,
  64688. configurable: true
  64689. });
  64690. RenderTargetTexture.prototype._onRatioRescale = function () {
  64691. if (this._sizeRatio) {
  64692. this.resize(this._initialSizeParameter);
  64693. }
  64694. };
  64695. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64696. get: function () {
  64697. return this._boundingBoxSize;
  64698. },
  64699. /**
  64700. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64701. * When defined, the cubemap will switch to local mode
  64702. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64703. * @example https://www.babylonjs-playground.com/#RNASML
  64704. */
  64705. set: function (value) {
  64706. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64707. return;
  64708. }
  64709. this._boundingBoxSize = value;
  64710. var scene = this.getScene();
  64711. if (scene) {
  64712. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64713. }
  64714. },
  64715. enumerable: true,
  64716. configurable: true
  64717. });
  64718. /**
  64719. * Creates a depth stencil texture.
  64720. * This is only available in WebGL 2 or with the depth texture extension available.
  64721. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64722. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64723. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64724. */
  64725. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64726. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64727. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64728. if (generateStencil === void 0) { generateStencil = false; }
  64729. if (!this.getScene()) {
  64730. return;
  64731. }
  64732. var engine = this.getScene().getEngine();
  64733. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64734. bilinearFiltering: bilinearFiltering,
  64735. comparisonFunction: comparisonFunction,
  64736. generateStencil: generateStencil,
  64737. isCube: this.isCube
  64738. });
  64739. engine.setFrameBufferDepthStencilTexture(this);
  64740. };
  64741. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64742. if (size.ratio) {
  64743. this._sizeRatio = size.ratio;
  64744. this._size = {
  64745. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64746. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64747. };
  64748. }
  64749. else {
  64750. this._size = size;
  64751. }
  64752. };
  64753. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64754. get: function () {
  64755. return this._samples;
  64756. },
  64757. set: function (value) {
  64758. if (this._samples === value) {
  64759. return;
  64760. }
  64761. var scene = this.getScene();
  64762. if (!scene) {
  64763. return;
  64764. }
  64765. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64766. },
  64767. enumerable: true,
  64768. configurable: true
  64769. });
  64770. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64771. this._currentRefreshId = -1;
  64772. };
  64773. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64774. get: function () {
  64775. return this._refreshRate;
  64776. },
  64777. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64778. set: function (value) {
  64779. this._refreshRate = value;
  64780. this.resetRefreshCounter();
  64781. },
  64782. enumerable: true,
  64783. configurable: true
  64784. });
  64785. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64786. if (!this._postProcessManager) {
  64787. var scene = this.getScene();
  64788. if (!scene) {
  64789. return;
  64790. }
  64791. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64792. this._postProcesses = new Array();
  64793. }
  64794. this._postProcesses.push(postProcess);
  64795. this._postProcesses[0].autoClear = false;
  64796. };
  64797. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64798. if (!this._postProcesses) {
  64799. return;
  64800. }
  64801. if (dispose) {
  64802. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64803. var postProcess = _a[_i];
  64804. postProcess.dispose();
  64805. }
  64806. }
  64807. this._postProcesses = [];
  64808. };
  64809. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64810. if (!this._postProcesses) {
  64811. return;
  64812. }
  64813. var index = this._postProcesses.indexOf(postProcess);
  64814. if (index === -1) {
  64815. return;
  64816. }
  64817. this._postProcesses.splice(index, 1);
  64818. if (this._postProcesses.length > 0) {
  64819. this._postProcesses[0].autoClear = false;
  64820. }
  64821. };
  64822. RenderTargetTexture.prototype._shouldRender = function () {
  64823. if (this._currentRefreshId === -1) { // At least render once
  64824. this._currentRefreshId = 1;
  64825. return true;
  64826. }
  64827. if (this.refreshRate === this._currentRefreshId) {
  64828. this._currentRefreshId = 1;
  64829. return true;
  64830. }
  64831. this._currentRefreshId++;
  64832. return false;
  64833. };
  64834. RenderTargetTexture.prototype.getRenderSize = function () {
  64835. if (this._size.width) {
  64836. return this._size.width;
  64837. }
  64838. return this._size;
  64839. };
  64840. RenderTargetTexture.prototype.getRenderWidth = function () {
  64841. if (this._size.width) {
  64842. return this._size.width;
  64843. }
  64844. return this._size;
  64845. };
  64846. RenderTargetTexture.prototype.getRenderHeight = function () {
  64847. if (this._size.width) {
  64848. return this._size.height;
  64849. }
  64850. return this._size;
  64851. };
  64852. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64853. get: function () {
  64854. return true;
  64855. },
  64856. enumerable: true,
  64857. configurable: true
  64858. });
  64859. RenderTargetTexture.prototype.scale = function (ratio) {
  64860. var newSize = this.getRenderSize() * ratio;
  64861. this.resize(newSize);
  64862. };
  64863. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64864. if (this.isCube) {
  64865. return this._textureMatrix;
  64866. }
  64867. return _super.prototype.getReflectionTextureMatrix.call(this);
  64868. };
  64869. RenderTargetTexture.prototype.resize = function (size) {
  64870. this.releaseInternalTexture();
  64871. var scene = this.getScene();
  64872. if (!scene) {
  64873. return;
  64874. }
  64875. this._processSizeParameter(size);
  64876. if (this.isCube) {
  64877. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64878. }
  64879. else {
  64880. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64881. }
  64882. };
  64883. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64884. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64885. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64886. var scene = this.getScene();
  64887. if (!scene) {
  64888. return;
  64889. }
  64890. var engine = scene.getEngine();
  64891. if (this.useCameraPostProcesses !== undefined) {
  64892. useCameraPostProcess = this.useCameraPostProcesses;
  64893. }
  64894. if (this._waitingRenderList) {
  64895. this.renderList = [];
  64896. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64897. var id = this._waitingRenderList[index];
  64898. var mesh_1 = scene.getMeshByID(id);
  64899. if (mesh_1) {
  64900. this.renderList.push(mesh_1);
  64901. }
  64902. }
  64903. delete this._waitingRenderList;
  64904. }
  64905. // Is predicate defined?
  64906. if (this.renderListPredicate) {
  64907. if (this.renderList) {
  64908. this.renderList.splice(0); // Clear previous renderList
  64909. }
  64910. else {
  64911. this.renderList = [];
  64912. }
  64913. var scene = this.getScene();
  64914. if (!scene) {
  64915. return;
  64916. }
  64917. var sceneMeshes = scene.meshes;
  64918. for (var index = 0; index < sceneMeshes.length; index++) {
  64919. var mesh = sceneMeshes[index];
  64920. if (this.renderListPredicate(mesh)) {
  64921. this.renderList.push(mesh);
  64922. }
  64923. }
  64924. }
  64925. this.onBeforeBindObservable.notifyObservers(this);
  64926. // Set custom projection.
  64927. // Needs to be before binding to prevent changing the aspect ratio.
  64928. var camera;
  64929. if (this.activeCamera) {
  64930. camera = this.activeCamera;
  64931. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64932. if (this.activeCamera !== scene.activeCamera) {
  64933. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64934. }
  64935. }
  64936. else {
  64937. camera = scene.activeCamera;
  64938. if (camera) {
  64939. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64940. }
  64941. }
  64942. // Prepare renderingManager
  64943. this._renderingManager.reset();
  64944. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64945. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64946. var sceneRenderId = scene.getRenderId();
  64947. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64948. var mesh = currentRenderList[meshIndex];
  64949. if (mesh) {
  64950. if (!mesh.isReady(this.refreshRate === 0)) {
  64951. this.resetRefreshCounter();
  64952. continue;
  64953. }
  64954. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64955. var isMasked = void 0;
  64956. if (!this.renderList && camera) {
  64957. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64958. }
  64959. else {
  64960. isMasked = false;
  64961. }
  64962. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64963. mesh._activate(sceneRenderId);
  64964. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64965. var subMesh = mesh.subMeshes[subIndex];
  64966. scene._activeIndices.addCount(subMesh.indexCount, false);
  64967. this._renderingManager.dispatch(subMesh, mesh);
  64968. }
  64969. }
  64970. }
  64971. }
  64972. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64973. var particleSystem = scene.particleSystems[particleIndex];
  64974. var emitter = particleSystem.emitter;
  64975. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64976. continue;
  64977. }
  64978. if (currentRenderList.indexOf(emitter) >= 0) {
  64979. this._renderingManager.dispatchParticles(particleSystem);
  64980. }
  64981. }
  64982. if (this.isCube) {
  64983. for (var face = 0; face < 6; face++) {
  64984. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64985. scene.incrementRenderId();
  64986. scene.resetCachedMaterial();
  64987. }
  64988. }
  64989. else {
  64990. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64991. }
  64992. this.onAfterUnbindObservable.notifyObservers(this);
  64993. if (scene.activeCamera) {
  64994. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64995. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64996. }
  64997. engine.setViewport(scene.activeCamera.viewport);
  64998. }
  64999. scene.resetCachedMaterial();
  65000. };
  65001. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65002. var minimum = 128;
  65003. var x = renderDimension * scale;
  65004. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65005. // Ensure we don't exceed the render dimension (while staying POT)
  65006. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65007. };
  65008. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65009. var _this = this;
  65010. if (!this._texture) {
  65011. return;
  65012. }
  65013. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65014. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65015. });
  65016. };
  65017. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65018. var scene = this.getScene();
  65019. if (!scene) {
  65020. return;
  65021. }
  65022. var engine = scene.getEngine();
  65023. if (!this._texture) {
  65024. return;
  65025. }
  65026. // Bind
  65027. if (this._postProcessManager) {
  65028. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65029. }
  65030. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65031. if (this._texture) {
  65032. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65033. }
  65034. }
  65035. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65036. // Clear
  65037. if (this.onClearObservable.hasObservers()) {
  65038. this.onClearObservable.notifyObservers(engine);
  65039. }
  65040. else {
  65041. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65042. }
  65043. if (!this._doNotChangeAspectRatio) {
  65044. scene.updateTransformMatrix(true);
  65045. }
  65046. // Render
  65047. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65048. if (this._postProcessManager) {
  65049. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65050. }
  65051. else if (useCameraPostProcess) {
  65052. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65053. }
  65054. if (!this._doNotChangeAspectRatio) {
  65055. scene.updateTransformMatrix(true);
  65056. }
  65057. // Dump ?
  65058. if (dumpForDebug) {
  65059. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65060. }
  65061. // Unbind
  65062. if (!this.isCube || faceIndex === 5) {
  65063. if (this.isCube) {
  65064. if (faceIndex === 5) {
  65065. engine.generateMipMapsForCubemap(this._texture);
  65066. }
  65067. }
  65068. this.unbindFrameBuffer(engine, faceIndex);
  65069. }
  65070. else {
  65071. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65072. }
  65073. };
  65074. /**
  65075. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65076. * This allowed control for front to back rendering or reversly depending of the special needs.
  65077. *
  65078. * @param renderingGroupId The rendering group id corresponding to its index
  65079. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65080. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65081. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65082. */
  65083. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65084. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65085. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65086. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65087. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65088. };
  65089. /**
  65090. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65091. *
  65092. * @param renderingGroupId The rendering group id corresponding to its index
  65093. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65094. */
  65095. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65096. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65097. };
  65098. RenderTargetTexture.prototype.clone = function () {
  65099. var textureSize = this.getSize();
  65100. 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);
  65101. // Base texture
  65102. newTexture.hasAlpha = this.hasAlpha;
  65103. newTexture.level = this.level;
  65104. // RenderTarget Texture
  65105. newTexture.coordinatesMode = this.coordinatesMode;
  65106. if (this.renderList) {
  65107. newTexture.renderList = this.renderList.slice(0);
  65108. }
  65109. return newTexture;
  65110. };
  65111. RenderTargetTexture.prototype.serialize = function () {
  65112. if (!this.name) {
  65113. return null;
  65114. }
  65115. var serializationObject = _super.prototype.serialize.call(this);
  65116. serializationObject.renderTargetSize = this.getRenderSize();
  65117. serializationObject.renderList = [];
  65118. if (this.renderList) {
  65119. for (var index = 0; index < this.renderList.length; index++) {
  65120. serializationObject.renderList.push(this.renderList[index].id);
  65121. }
  65122. }
  65123. return serializationObject;
  65124. };
  65125. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  65126. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  65127. var objBuffer = this.getInternalTexture();
  65128. var scene = this.getScene();
  65129. if (objBuffer && scene) {
  65130. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  65131. }
  65132. };
  65133. RenderTargetTexture.prototype.dispose = function () {
  65134. if (this._postProcessManager) {
  65135. this._postProcessManager.dispose();
  65136. this._postProcessManager = null;
  65137. }
  65138. this.clearPostProcesses(true);
  65139. if (this._resizeObserver) {
  65140. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  65141. this._resizeObserver = null;
  65142. }
  65143. this.renderList = null;
  65144. // Remove from custom render targets
  65145. var scene = this.getScene();
  65146. if (!scene) {
  65147. return;
  65148. }
  65149. var index = scene.customRenderTargets.indexOf(this);
  65150. if (index >= 0) {
  65151. scene.customRenderTargets.splice(index, 1);
  65152. }
  65153. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  65154. var camera = _a[_i];
  65155. index = camera.customRenderTargets.indexOf(this);
  65156. if (index >= 0) {
  65157. camera.customRenderTargets.splice(index, 1);
  65158. }
  65159. }
  65160. _super.prototype.dispose.call(this);
  65161. };
  65162. RenderTargetTexture.prototype._rebuild = function () {
  65163. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65164. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65165. }
  65166. if (this._postProcessManager) {
  65167. this._postProcessManager._rebuild();
  65168. }
  65169. };
  65170. /**
  65171. * Clear the info related to rendering groups preventing retention point in material dispose.
  65172. */
  65173. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  65174. if (this._renderingManager) {
  65175. this._renderingManager.freeRenderingGroups();
  65176. }
  65177. };
  65178. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  65179. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  65180. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  65181. return RenderTargetTexture;
  65182. }(BABYLON.Texture));
  65183. BABYLON.RenderTargetTexture = RenderTargetTexture;
  65184. })(BABYLON || (BABYLON = {}));
  65185. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  65186. var BABYLON;
  65187. (function (BABYLON) {
  65188. ;
  65189. var MultiRenderTarget = /** @class */ (function (_super) {
  65190. __extends(MultiRenderTarget, _super);
  65191. function MultiRenderTarget(name, size, count, scene, options) {
  65192. var _this = this;
  65193. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  65194. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  65195. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  65196. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  65197. _this._engine = scene.getEngine();
  65198. if (!_this.isSupported) {
  65199. _this.dispose();
  65200. return;
  65201. }
  65202. var types = [];
  65203. var samplingModes = [];
  65204. for (var i = 0; i < count; i++) {
  65205. if (options && options.types && options.types[i] !== undefined) {
  65206. types.push(options.types[i]);
  65207. }
  65208. else {
  65209. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65210. }
  65211. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  65212. samplingModes.push(options.samplingModes[i]);
  65213. }
  65214. else {
  65215. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65216. }
  65217. }
  65218. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  65219. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  65220. _this._size = size;
  65221. _this._multiRenderTargetOptions = {
  65222. samplingModes: samplingModes,
  65223. generateMipMaps: generateMipMaps,
  65224. generateDepthBuffer: generateDepthBuffer,
  65225. generateStencilBuffer: generateStencilBuffer,
  65226. generateDepthTexture: generateDepthTexture,
  65227. types: types,
  65228. textureCount: count
  65229. };
  65230. _this._createInternalTextures();
  65231. _this._createTextures();
  65232. return _this;
  65233. }
  65234. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  65235. get: function () {
  65236. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  65237. },
  65238. enumerable: true,
  65239. configurable: true
  65240. });
  65241. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  65242. get: function () {
  65243. return this._textures;
  65244. },
  65245. enumerable: true,
  65246. configurable: true
  65247. });
  65248. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  65249. get: function () {
  65250. return this._textures[this._textures.length - 1];
  65251. },
  65252. enumerable: true,
  65253. configurable: true
  65254. });
  65255. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  65256. set: function (wrap) {
  65257. if (this._textures) {
  65258. for (var i = 0; i < this._textures.length; i++) {
  65259. this._textures[i].wrapU = wrap;
  65260. }
  65261. }
  65262. },
  65263. enumerable: true,
  65264. configurable: true
  65265. });
  65266. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  65267. set: function (wrap) {
  65268. if (this._textures) {
  65269. for (var i = 0; i < this._textures.length; i++) {
  65270. this._textures[i].wrapV = wrap;
  65271. }
  65272. }
  65273. },
  65274. enumerable: true,
  65275. configurable: true
  65276. });
  65277. MultiRenderTarget.prototype._rebuild = function () {
  65278. this.releaseInternalTextures();
  65279. this._createInternalTextures();
  65280. for (var i = 0; i < this._internalTextures.length; i++) {
  65281. var texture = this._textures[i];
  65282. texture._texture = this._internalTextures[i];
  65283. }
  65284. // Keeps references to frame buffer and stencil/depth buffer
  65285. this._texture = this._internalTextures[0];
  65286. };
  65287. MultiRenderTarget.prototype._createInternalTextures = function () {
  65288. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  65289. };
  65290. MultiRenderTarget.prototype._createTextures = function () {
  65291. this._textures = [];
  65292. for (var i = 0; i < this._internalTextures.length; i++) {
  65293. var texture = new BABYLON.Texture(null, this.getScene());
  65294. texture._texture = this._internalTextures[i];
  65295. this._textures.push(texture);
  65296. }
  65297. // Keeps references to frame buffer and stencil/depth buffer
  65298. this._texture = this._internalTextures[0];
  65299. };
  65300. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  65301. get: function () {
  65302. return this._samples;
  65303. },
  65304. set: function (value) {
  65305. if (this._samples === value) {
  65306. return;
  65307. }
  65308. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  65309. },
  65310. enumerable: true,
  65311. configurable: true
  65312. });
  65313. MultiRenderTarget.prototype.resize = function (size) {
  65314. this.releaseInternalTextures();
  65315. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  65316. this._createInternalTextures();
  65317. };
  65318. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65319. var _this = this;
  65320. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  65321. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65322. });
  65323. };
  65324. MultiRenderTarget.prototype.dispose = function () {
  65325. this.releaseInternalTextures();
  65326. _super.prototype.dispose.call(this);
  65327. };
  65328. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  65329. if (!this._internalTextures) {
  65330. return;
  65331. }
  65332. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  65333. if (this._internalTextures[i] !== undefined) {
  65334. this._internalTextures[i].dispose();
  65335. this._internalTextures.splice(i, 1);
  65336. }
  65337. }
  65338. };
  65339. return MultiRenderTarget;
  65340. }(BABYLON.RenderTargetTexture));
  65341. BABYLON.MultiRenderTarget = MultiRenderTarget;
  65342. })(BABYLON || (BABYLON = {}));
  65343. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  65344. var BABYLON;
  65345. (function (BABYLON) {
  65346. var MirrorTexture = /** @class */ (function (_super) {
  65347. __extends(MirrorTexture, _super);
  65348. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  65349. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65351. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65352. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  65353. _this.scene = scene;
  65354. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  65355. _this._transformMatrix = BABYLON.Matrix.Zero();
  65356. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  65357. _this._adaptiveBlurKernel = 0;
  65358. _this._blurKernelX = 0;
  65359. _this._blurKernelY = 0;
  65360. _this._blurRatio = 1.0;
  65361. _this.ignoreCameraViewport = true;
  65362. _this._updateGammaSpace();
  65363. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  65364. _this._updateGammaSpace;
  65365. });
  65366. _this.onBeforeRenderObservable.add(function () {
  65367. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  65368. _this._savedViewMatrix = scene.getViewMatrix();
  65369. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  65370. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  65371. scene.clipPlane = _this.mirrorPlane;
  65372. scene.getEngine().cullBackFaces = false;
  65373. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  65374. });
  65375. _this.onAfterRenderObservable.add(function () {
  65376. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  65377. scene.getEngine().cullBackFaces = true;
  65378. scene._mirroredCameraPosition = null;
  65379. delete scene.clipPlane;
  65380. });
  65381. return _this;
  65382. }
  65383. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  65384. get: function () {
  65385. return this._blurRatio;
  65386. },
  65387. set: function (value) {
  65388. if (this._blurRatio === value) {
  65389. return;
  65390. }
  65391. this._blurRatio = value;
  65392. this._preparePostProcesses();
  65393. },
  65394. enumerable: true,
  65395. configurable: true
  65396. });
  65397. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  65398. set: function (value) {
  65399. this._adaptiveBlurKernel = value;
  65400. this._autoComputeBlurKernel();
  65401. },
  65402. enumerable: true,
  65403. configurable: true
  65404. });
  65405. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  65406. set: function (value) {
  65407. this.blurKernelX = value;
  65408. this.blurKernelY = value;
  65409. },
  65410. enumerable: true,
  65411. configurable: true
  65412. });
  65413. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  65414. get: function () {
  65415. return this._blurKernelX;
  65416. },
  65417. set: function (value) {
  65418. if (this._blurKernelX === value) {
  65419. return;
  65420. }
  65421. this._blurKernelX = value;
  65422. this._preparePostProcesses();
  65423. },
  65424. enumerable: true,
  65425. configurable: true
  65426. });
  65427. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  65428. get: function () {
  65429. return this._blurKernelY;
  65430. },
  65431. set: function (value) {
  65432. if (this._blurKernelY === value) {
  65433. return;
  65434. }
  65435. this._blurKernelY = value;
  65436. this._preparePostProcesses();
  65437. },
  65438. enumerable: true,
  65439. configurable: true
  65440. });
  65441. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  65442. var engine = this.getScene().getEngine();
  65443. var dw = this.getRenderWidth() / engine.getRenderWidth();
  65444. var dh = this.getRenderHeight() / engine.getRenderHeight();
  65445. this.blurKernelX = this._adaptiveBlurKernel * dw;
  65446. this.blurKernelY = this._adaptiveBlurKernel * dh;
  65447. };
  65448. MirrorTexture.prototype._onRatioRescale = function () {
  65449. if (this._sizeRatio) {
  65450. this.resize(this._initialSizeParameter);
  65451. if (!this._adaptiveBlurKernel) {
  65452. this._preparePostProcesses();
  65453. }
  65454. }
  65455. if (this._adaptiveBlurKernel) {
  65456. this._autoComputeBlurKernel();
  65457. }
  65458. };
  65459. MirrorTexture.prototype._updateGammaSpace = function () {
  65460. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  65461. };
  65462. MirrorTexture.prototype._preparePostProcesses = function () {
  65463. this.clearPostProcesses(true);
  65464. if (this._blurKernelX && this._blurKernelY) {
  65465. var engine = this.getScene().getEngine();
  65466. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65467. 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);
  65468. this._blurX.autoClear = false;
  65469. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  65470. this._blurX.inputTexture = this._texture;
  65471. }
  65472. else {
  65473. this._blurX.alwaysForcePOT = true;
  65474. }
  65475. 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);
  65476. this._blurY.autoClear = false;
  65477. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  65478. this.addPostProcess(this._blurX);
  65479. this.addPostProcess(this._blurY);
  65480. }
  65481. else {
  65482. if (this._blurY) {
  65483. this.removePostProcess(this._blurY);
  65484. this._blurY.dispose();
  65485. this._blurY = null;
  65486. }
  65487. if (this._blurX) {
  65488. this.removePostProcess(this._blurX);
  65489. this._blurX.dispose();
  65490. this._blurX = null;
  65491. }
  65492. }
  65493. };
  65494. MirrorTexture.prototype.clone = function () {
  65495. var scene = this.getScene();
  65496. if (!scene) {
  65497. return this;
  65498. }
  65499. var textureSize = this.getSize();
  65500. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  65501. // Base texture
  65502. newTexture.hasAlpha = this.hasAlpha;
  65503. newTexture.level = this.level;
  65504. // Mirror Texture
  65505. newTexture.mirrorPlane = this.mirrorPlane.clone();
  65506. if (this.renderList) {
  65507. newTexture.renderList = this.renderList.slice(0);
  65508. }
  65509. return newTexture;
  65510. };
  65511. MirrorTexture.prototype.serialize = function () {
  65512. if (!this.name) {
  65513. return null;
  65514. }
  65515. var serializationObject = _super.prototype.serialize.call(this);
  65516. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  65517. return serializationObject;
  65518. };
  65519. MirrorTexture.prototype.dispose = function () {
  65520. _super.prototype.dispose.call(this);
  65521. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  65522. };
  65523. return MirrorTexture;
  65524. }(BABYLON.RenderTargetTexture));
  65525. BABYLON.MirrorTexture = MirrorTexture;
  65526. })(BABYLON || (BABYLON = {}));
  65527. //# sourceMappingURL=babylon.mirrorTexture.js.map
  65528. var BABYLON;
  65529. (function (BABYLON) {
  65530. /**
  65531. * Creates a refraction texture used by refraction channel of the standard material.
  65532. * @param name the texture name
  65533. * @param size size of the underlying texture
  65534. * @param scene root scene
  65535. */
  65536. var RefractionTexture = /** @class */ (function (_super) {
  65537. __extends(RefractionTexture, _super);
  65538. function RefractionTexture(name, size, scene, generateMipMaps) {
  65539. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  65540. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  65541. _this.depth = 2.0;
  65542. _this.onBeforeRenderObservable.add(function () {
  65543. scene.clipPlane = _this.refractionPlane;
  65544. });
  65545. _this.onAfterRenderObservable.add(function () {
  65546. delete scene.clipPlane;
  65547. });
  65548. return _this;
  65549. }
  65550. RefractionTexture.prototype.clone = function () {
  65551. var scene = this.getScene();
  65552. if (!scene) {
  65553. return this;
  65554. }
  65555. var textureSize = this.getSize();
  65556. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  65557. // Base texture
  65558. newTexture.hasAlpha = this.hasAlpha;
  65559. newTexture.level = this.level;
  65560. // Refraction Texture
  65561. newTexture.refractionPlane = this.refractionPlane.clone();
  65562. if (this.renderList) {
  65563. newTexture.renderList = this.renderList.slice(0);
  65564. }
  65565. newTexture.depth = this.depth;
  65566. return newTexture;
  65567. };
  65568. RefractionTexture.prototype.serialize = function () {
  65569. if (!this.name) {
  65570. return null;
  65571. }
  65572. var serializationObject = _super.prototype.serialize.call(this);
  65573. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  65574. serializationObject.depth = this.depth;
  65575. return serializationObject;
  65576. };
  65577. return RefractionTexture;
  65578. }(BABYLON.RenderTargetTexture));
  65579. BABYLON.RefractionTexture = RefractionTexture;
  65580. })(BABYLON || (BABYLON = {}));
  65581. //# sourceMappingURL=babylon.refractionTexture.js.map
  65582. var BABYLON;
  65583. (function (BABYLON) {
  65584. /**
  65585. * A class extending {BABYLON.Texture} allowing drawing on a texture
  65586. * @see http://doc.babylonjs.com/how_to/dynamictexture
  65587. */
  65588. var DynamicTexture = /** @class */ (function (_super) {
  65589. __extends(DynamicTexture, _super);
  65590. /**
  65591. * Creates a {BABYLON.DynamicTexture}
  65592. * @param name defines the name of the texture
  65593. * @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
  65594. * @param scene defines the scene where you want the texture
  65595. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  65596. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  65597. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  65598. */
  65599. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  65600. if (scene === void 0) { scene = null; }
  65601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65602. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65603. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  65604. _this.name = name;
  65605. _this._engine = _this.getScene().getEngine();
  65606. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65607. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65608. _this._generateMipMaps = generateMipMaps;
  65609. if (options.getContext) {
  65610. _this._canvas = options;
  65611. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65612. }
  65613. else {
  65614. _this._canvas = document.createElement("canvas");
  65615. if (options.width || options.width === 0) {
  65616. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  65617. }
  65618. else {
  65619. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  65620. }
  65621. }
  65622. var textureSize = _this.getSize();
  65623. _this._canvas.width = textureSize.width;
  65624. _this._canvas.height = textureSize.height;
  65625. _this._context = _this._canvas.getContext("2d");
  65626. return _this;
  65627. }
  65628. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  65629. /**
  65630. * Gets the current state of canRescale
  65631. */
  65632. get: function () {
  65633. return true;
  65634. },
  65635. enumerable: true,
  65636. configurable: true
  65637. });
  65638. DynamicTexture.prototype._recreate = function (textureSize) {
  65639. this._canvas.width = textureSize.width;
  65640. this._canvas.height = textureSize.height;
  65641. this.releaseInternalTexture();
  65642. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  65643. };
  65644. /**
  65645. * Scales the texture
  65646. * @param ratio the scale factor to apply to both width and height
  65647. */
  65648. DynamicTexture.prototype.scale = function (ratio) {
  65649. var textureSize = this.getSize();
  65650. textureSize.width *= ratio;
  65651. textureSize.height *= ratio;
  65652. this._recreate(textureSize);
  65653. };
  65654. /**
  65655. * Resizes the texture
  65656. * @param width the new width
  65657. * @param height the new height
  65658. */
  65659. DynamicTexture.prototype.scaleTo = function (width, height) {
  65660. var textureSize = this.getSize();
  65661. textureSize.width = width;
  65662. textureSize.height = height;
  65663. this._recreate(textureSize);
  65664. };
  65665. /**
  65666. * Gets the context of the canvas used by the texture
  65667. * @returns the canvas context of the dynamic texture
  65668. */
  65669. DynamicTexture.prototype.getContext = function () {
  65670. return this._context;
  65671. };
  65672. /**
  65673. * Clears the texture
  65674. */
  65675. DynamicTexture.prototype.clear = function () {
  65676. var size = this.getSize();
  65677. this._context.fillRect(0, 0, size.width, size.height);
  65678. };
  65679. /**
  65680. * Updates the texture
  65681. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65682. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65683. */
  65684. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65685. if (premulAlpha === void 0) { premulAlpha = false; }
  65686. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65687. };
  65688. /**
  65689. * Draws text onto the texture
  65690. * @param text defines the text to be drawn
  65691. * @param x defines the placement of the text from the left
  65692. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65693. * @param font defines the font to be used with font-style, font-size, font-name
  65694. * @param color defines the color used for the text
  65695. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65696. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65697. * @param update defines whether texture is immediately update (default is true)
  65698. */
  65699. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65700. if (update === void 0) { update = true; }
  65701. var size = this.getSize();
  65702. if (clearColor) {
  65703. this._context.fillStyle = clearColor;
  65704. this._context.fillRect(0, 0, size.width, size.height);
  65705. }
  65706. this._context.font = font;
  65707. if (x === null || x === undefined) {
  65708. var textSize = this._context.measureText(text);
  65709. x = (size.width - textSize.width) / 2;
  65710. }
  65711. if (y === null || y === undefined) {
  65712. var fontSize = parseInt((font.replace(/\D/g, '')));
  65713. y = (size.height / 2) + (fontSize / 3.65);
  65714. }
  65715. this._context.fillStyle = color;
  65716. this._context.fillText(text, x, y);
  65717. if (update) {
  65718. this.update(invertY);
  65719. }
  65720. };
  65721. /**
  65722. * Clones the texture
  65723. * @returns the clone of the texture.
  65724. */
  65725. DynamicTexture.prototype.clone = function () {
  65726. var scene = this.getScene();
  65727. if (!scene) {
  65728. return this;
  65729. }
  65730. var textureSize = this.getSize();
  65731. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65732. // Base texture
  65733. newTexture.hasAlpha = this.hasAlpha;
  65734. newTexture.level = this.level;
  65735. // Dynamic Texture
  65736. newTexture.wrapU = this.wrapU;
  65737. newTexture.wrapV = this.wrapV;
  65738. return newTexture;
  65739. };
  65740. /** @hidden */
  65741. DynamicTexture.prototype._rebuild = function () {
  65742. this.update();
  65743. };
  65744. return DynamicTexture;
  65745. }(BABYLON.Texture));
  65746. BABYLON.DynamicTexture = DynamicTexture;
  65747. })(BABYLON || (BABYLON = {}));
  65748. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65749. var BABYLON;
  65750. (function (BABYLON) {
  65751. var VideoTexture = /** @class */ (function (_super) {
  65752. __extends(VideoTexture, _super);
  65753. /**
  65754. * Creates a video texture.
  65755. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65756. * @param {string | null} name optional name, will detect from video source, if not defined
  65757. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65758. * @param {BABYLON.Scene} scene is obviously the current scene.
  65759. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65760. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65761. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65762. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65763. */
  65764. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65765. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65766. if (invertY === void 0) { invertY = false; }
  65767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65768. if (settings === void 0) { settings = {
  65769. autoPlay: true,
  65770. loop: true,
  65771. autoUpdateTexture: true,
  65772. }; }
  65773. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65774. _this._onUserActionRequestedObservable = null;
  65775. _this._stillImageCaptured = false;
  65776. _this._poster = false;
  65777. _this._createInternalTexture = function () {
  65778. if (_this._texture != null) {
  65779. if (_this._poster) {
  65780. _this._texture.dispose();
  65781. _this._poster = false;
  65782. }
  65783. else {
  65784. return;
  65785. }
  65786. }
  65787. if (!_this._engine.needPOTTextures ||
  65788. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65789. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65790. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65791. }
  65792. else {
  65793. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65794. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65795. _this._generateMipMaps = false;
  65796. }
  65797. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65798. if (!_this.video.autoplay) {
  65799. var oldHandler_1 = _this.video.onplaying;
  65800. var error_1 = false;
  65801. _this.video.onplaying = function () {
  65802. _this.video.onplaying = oldHandler_1;
  65803. _this._texture.isReady = true;
  65804. _this._updateInternalTexture();
  65805. if (!error_1) {
  65806. _this.video.pause();
  65807. }
  65808. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65809. _this.onLoadObservable.notifyObservers(_this);
  65810. }
  65811. };
  65812. var playing = _this.video.play();
  65813. if (playing) {
  65814. playing.then(function () {
  65815. // Everything is good.
  65816. })
  65817. .catch(function () {
  65818. error_1 = true;
  65819. // On Chrome for instance, new policies might prevent playing without user interaction.
  65820. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  65821. _this._onUserActionRequestedObservable.notifyObservers(_this);
  65822. }
  65823. });
  65824. }
  65825. else {
  65826. _this.video.onplaying = oldHandler_1;
  65827. _this._texture.isReady = true;
  65828. _this._updateInternalTexture();
  65829. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65830. _this.onLoadObservable.notifyObservers(_this);
  65831. }
  65832. }
  65833. }
  65834. else {
  65835. _this._texture.isReady = true;
  65836. _this._updateInternalTexture();
  65837. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65838. _this.onLoadObservable.notifyObservers(_this);
  65839. }
  65840. }
  65841. };
  65842. _this.reset = function () {
  65843. if (_this._texture == null) {
  65844. return;
  65845. }
  65846. if (!_this._poster) {
  65847. _this._texture.dispose();
  65848. _this._texture = null;
  65849. }
  65850. };
  65851. _this._updateInternalTexture = function (e) {
  65852. if (_this._texture == null || !_this._texture.isReady) {
  65853. return;
  65854. }
  65855. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65856. return;
  65857. }
  65858. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65859. };
  65860. _this._engine = _this.getScene().getEngine();
  65861. _this._generateMipMaps = generateMipMaps;
  65862. _this._samplingMode = samplingMode;
  65863. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65864. _this.name = name || _this._getName(src);
  65865. _this.video = _this._getVideo(src);
  65866. if (settings.poster) {
  65867. _this.video.poster = settings.poster;
  65868. }
  65869. if (settings.autoPlay !== undefined) {
  65870. _this.video.autoplay = settings.autoPlay;
  65871. }
  65872. if (settings.loop !== undefined) {
  65873. _this.video.loop = settings.loop;
  65874. }
  65875. _this.video.setAttribute("playsinline", "");
  65876. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65877. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65878. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65879. _this.video.addEventListener("emptied", _this.reset);
  65880. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65881. _this._createInternalTexture();
  65882. }
  65883. if (settings.poster) {
  65884. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  65885. _this._poster = true;
  65886. }
  65887. return _this;
  65888. }
  65889. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65890. get: function () {
  65891. if (!this._onUserActionRequestedObservable) {
  65892. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65893. }
  65894. return this._onUserActionRequestedObservable;
  65895. },
  65896. enumerable: true,
  65897. configurable: true
  65898. });
  65899. VideoTexture.prototype._getName = function (src) {
  65900. if (src instanceof HTMLVideoElement) {
  65901. return src.currentSrc;
  65902. }
  65903. if (typeof src === "object") {
  65904. return src.toString();
  65905. }
  65906. return src;
  65907. };
  65908. ;
  65909. VideoTexture.prototype._getVideo = function (src) {
  65910. if (src instanceof HTMLVideoElement) {
  65911. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65912. return src;
  65913. }
  65914. var video = document.createElement("video");
  65915. if (typeof src === "string") {
  65916. BABYLON.Tools.SetCorsBehavior(src, video);
  65917. video.src = src;
  65918. }
  65919. else {
  65920. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65921. src.forEach(function (url) {
  65922. var source = document.createElement("source");
  65923. source.src = url;
  65924. video.appendChild(source);
  65925. });
  65926. }
  65927. return video;
  65928. };
  65929. ;
  65930. /**
  65931. * Internal method to initiate `update`.
  65932. */
  65933. VideoTexture.prototype._rebuild = function () {
  65934. this.update();
  65935. };
  65936. /**
  65937. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65938. */
  65939. VideoTexture.prototype.update = function () {
  65940. if (!this.autoUpdateTexture) {
  65941. // Expecting user to call `updateTexture` manually
  65942. return;
  65943. }
  65944. this.updateTexture(true);
  65945. };
  65946. /**
  65947. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65948. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65949. */
  65950. VideoTexture.prototype.updateTexture = function (isVisible) {
  65951. if (!isVisible) {
  65952. return;
  65953. }
  65954. if (this.video.paused && this._stillImageCaptured) {
  65955. return;
  65956. }
  65957. this._stillImageCaptured = true;
  65958. this._updateInternalTexture();
  65959. };
  65960. /**
  65961. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65962. * @param url New url.
  65963. */
  65964. VideoTexture.prototype.updateURL = function (url) {
  65965. this.video.src = url;
  65966. };
  65967. VideoTexture.prototype.dispose = function () {
  65968. _super.prototype.dispose.call(this);
  65969. if (this._onUserActionRequestedObservable) {
  65970. this._onUserActionRequestedObservable.clear();
  65971. this._onUserActionRequestedObservable = null;
  65972. }
  65973. this.video.removeEventListener("canplay", this._createInternalTexture);
  65974. this.video.removeEventListener("paused", this._updateInternalTexture);
  65975. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65976. this.video.removeEventListener("emptied", this.reset);
  65977. this.video.pause();
  65978. };
  65979. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65980. var video = document.createElement("video");
  65981. video.setAttribute('autoplay', '');
  65982. video.setAttribute('muted', '');
  65983. video.setAttribute('playsinline', '');
  65984. var constraintsDeviceId;
  65985. if (constraints && constraints.deviceId) {
  65986. constraintsDeviceId = {
  65987. exact: constraints.deviceId,
  65988. };
  65989. }
  65990. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65991. if (navigator.mediaDevices) {
  65992. navigator.mediaDevices.getUserMedia({ video: constraints })
  65993. .then(function (stream) {
  65994. if (video.mozSrcObject !== undefined) {
  65995. // hack for Firefox < 19
  65996. video.mozSrcObject = stream;
  65997. }
  65998. else {
  65999. video.srcObject = stream;
  66000. }
  66001. var onPlaying = function () {
  66002. if (onReady) {
  66003. onReady(new VideoTexture("video", video, scene, true, true));
  66004. }
  66005. video.removeEventListener("playing", onPlaying);
  66006. };
  66007. video.addEventListener("playing", onPlaying);
  66008. video.play();
  66009. })
  66010. .catch(function (err) {
  66011. BABYLON.Tools.Error(err.name);
  66012. });
  66013. }
  66014. else {
  66015. navigator.getUserMedia =
  66016. navigator.getUserMedia ||
  66017. navigator.webkitGetUserMedia ||
  66018. navigator.mozGetUserMedia ||
  66019. navigator.msGetUserMedia;
  66020. if (navigator.getUserMedia) {
  66021. navigator.getUserMedia({
  66022. video: {
  66023. deviceId: constraintsDeviceId,
  66024. width: {
  66025. min: (constraints && constraints.minWidth) || 256,
  66026. max: (constraints && constraints.maxWidth) || 640,
  66027. },
  66028. height: {
  66029. min: (constraints && constraints.minHeight) || 256,
  66030. max: (constraints && constraints.maxHeight) || 480,
  66031. },
  66032. },
  66033. }, function (stream) {
  66034. if (video.mozSrcObject !== undefined) {
  66035. // hack for Firefox < 19
  66036. video.mozSrcObject = stream;
  66037. }
  66038. else {
  66039. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66040. }
  66041. video.play();
  66042. if (onReady) {
  66043. onReady(new VideoTexture("video", video, scene, true, true));
  66044. }
  66045. }, function (e) {
  66046. BABYLON.Tools.Error(e.name);
  66047. });
  66048. }
  66049. }
  66050. };
  66051. return VideoTexture;
  66052. }(BABYLON.Texture));
  66053. BABYLON.VideoTexture = VideoTexture;
  66054. })(BABYLON || (BABYLON = {}));
  66055. //# sourceMappingURL=babylon.videoTexture.js.map
  66056. var BABYLON;
  66057. (function (BABYLON) {
  66058. var RawTexture = /** @class */ (function (_super) {
  66059. __extends(RawTexture, _super);
  66060. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66061. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66062. if (invertY === void 0) { invertY = false; }
  66063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66064. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66065. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66066. _this.format = format;
  66067. _this._engine = scene.getEngine();
  66068. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66069. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66070. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66071. return _this;
  66072. }
  66073. RawTexture.prototype.update = function (data) {
  66074. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66075. };
  66076. // Statics
  66077. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66078. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66079. if (invertY === void 0) { invertY = false; }
  66080. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66081. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66082. };
  66083. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66084. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66085. if (invertY === void 0) { invertY = false; }
  66086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66087. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66088. };
  66089. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66090. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66091. if (invertY === void 0) { invertY = false; }
  66092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66093. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66094. };
  66095. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66096. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66097. if (invertY === void 0) { invertY = false; }
  66098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66099. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66100. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  66101. };
  66102. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66103. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66104. if (invertY === void 0) { invertY = false; }
  66105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66106. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66107. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  66108. };
  66109. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66110. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66111. if (invertY === void 0) { invertY = false; }
  66112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66113. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66114. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  66115. };
  66116. return RawTexture;
  66117. }(BABYLON.Texture));
  66118. BABYLON.RawTexture = RawTexture;
  66119. })(BABYLON || (BABYLON = {}));
  66120. //# sourceMappingURL=babylon.rawTexture.js.map
  66121. var BABYLON;
  66122. (function (BABYLON) {
  66123. /**
  66124. * Class used to store 3D textures containing user data
  66125. */
  66126. var RawTexture3D = /** @class */ (function (_super) {
  66127. __extends(RawTexture3D, _super);
  66128. /**
  66129. * Create a new RawTexture3D
  66130. * @param data defines the data of the texture
  66131. * @param width defines the width of the texture
  66132. * @param height defines the height of the texture
  66133. * @param depth defines the depth of the texture
  66134. * @param format defines the texture format to use
  66135. * @param scene defines the hosting scene
  66136. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  66137. * @param invertY defines if texture must be stored with Y axis inverted
  66138. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  66139. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  66140. */
  66141. function RawTexture3D(data, width, height, depth,
  66142. /** Gets or sets the texture format to use */
  66143. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  66144. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66145. if (invertY === void 0) { invertY = false; }
  66146. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66147. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66148. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66149. _this.format = format;
  66150. _this._engine = scene.getEngine();
  66151. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  66152. _this.is3D = true;
  66153. return _this;
  66154. }
  66155. /**
  66156. * Update the texture with new data
  66157. * @param data defines the data to store in the texture
  66158. */
  66159. RawTexture3D.prototype.update = function (data) {
  66160. if (!this._texture) {
  66161. return;
  66162. }
  66163. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66164. };
  66165. return RawTexture3D;
  66166. }(BABYLON.Texture));
  66167. BABYLON.RawTexture3D = RawTexture3D;
  66168. })(BABYLON || (BABYLON = {}));
  66169. //# sourceMappingURL=babylon.rawTexture3D.js.map
  66170. var BABYLON;
  66171. (function (BABYLON) {
  66172. /**
  66173. * PostProcessManager is used to manage one or more post processes or post process pipelines
  66174. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66175. */
  66176. var PostProcessManager = /** @class */ (function () {
  66177. /**
  66178. * Creates a new instance PostProcess
  66179. * @param scene The scene that the post process is associated with.
  66180. */
  66181. function PostProcessManager(scene) {
  66182. this._vertexBuffers = {};
  66183. this._scene = scene;
  66184. }
  66185. PostProcessManager.prototype._prepareBuffers = function () {
  66186. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  66187. return;
  66188. }
  66189. // VBO
  66190. var vertices = [];
  66191. vertices.push(1, 1);
  66192. vertices.push(-1, 1);
  66193. vertices.push(-1, -1);
  66194. vertices.push(1, -1);
  66195. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66196. this._buildIndexBuffer();
  66197. };
  66198. PostProcessManager.prototype._buildIndexBuffer = function () {
  66199. // Indices
  66200. var indices = [];
  66201. indices.push(0);
  66202. indices.push(1);
  66203. indices.push(2);
  66204. indices.push(0);
  66205. indices.push(2);
  66206. indices.push(3);
  66207. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  66208. };
  66209. /**
  66210. * Rebuilds the vertex buffers of the manager.
  66211. */
  66212. PostProcessManager.prototype._rebuild = function () {
  66213. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66214. if (!vb) {
  66215. return;
  66216. }
  66217. vb._rebuild();
  66218. this._buildIndexBuffer();
  66219. };
  66220. // Methods
  66221. /**
  66222. * Prepares a frame to be run through a post process.
  66223. * @param sourceTexture The input texture to the post procesess. (default: null)
  66224. * @param postProcesses An array of post processes to be run. (default: null)
  66225. * @returns True if the post processes were able to be run.
  66226. */
  66227. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  66228. if (sourceTexture === void 0) { sourceTexture = null; }
  66229. if (postProcesses === void 0) { postProcesses = null; }
  66230. var camera = this._scene.activeCamera;
  66231. if (!camera) {
  66232. return false;
  66233. }
  66234. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66235. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66236. return false;
  66237. }
  66238. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  66239. return true;
  66240. };
  66241. /**
  66242. * Manually render a set of post processes to a texture.
  66243. * @param postProcesses An array of post processes to be run.
  66244. * @param targetTexture The target texture to render to.
  66245. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  66246. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  66247. * @param lodLevel defines which lod of the texture to render to
  66248. */
  66249. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  66250. if (targetTexture === void 0) { targetTexture = null; }
  66251. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66252. if (faceIndex === void 0) { faceIndex = 0; }
  66253. if (lodLevel === void 0) { lodLevel = 0; }
  66254. var engine = this._scene.getEngine();
  66255. for (var index = 0; index < postProcesses.length; index++) {
  66256. if (index < postProcesses.length - 1) {
  66257. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  66258. }
  66259. else {
  66260. if (targetTexture) {
  66261. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  66262. }
  66263. else {
  66264. engine.restoreDefaultFramebuffer();
  66265. }
  66266. }
  66267. var pp = postProcesses[index];
  66268. var effect = pp.apply();
  66269. if (effect) {
  66270. pp.onBeforeRenderObservable.notifyObservers(effect);
  66271. // VBOs
  66272. this._prepareBuffers();
  66273. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66274. // Draw order
  66275. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66276. pp.onAfterRenderObservable.notifyObservers(effect);
  66277. }
  66278. }
  66279. // Restore depth buffer
  66280. engine.setDepthBuffer(true);
  66281. engine.setDepthWrite(true);
  66282. };
  66283. /**
  66284. * Finalize the result of the output of the postprocesses.
  66285. * @param doNotPresent If true the result will not be displayed to the screen.
  66286. * @param targetTexture The target texture to render to.
  66287. * @param faceIndex The index of the face to bind the target texture to.
  66288. * @param postProcesses The array of post processes to render.
  66289. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  66290. */
  66291. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  66292. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66293. var camera = this._scene.activeCamera;
  66294. if (!camera) {
  66295. return;
  66296. }
  66297. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66298. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66299. return;
  66300. }
  66301. var engine = this._scene.getEngine();
  66302. for (var index = 0, len = postProcesses.length; index < len; index++) {
  66303. var pp = postProcesses[index];
  66304. if (index < len - 1) {
  66305. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  66306. }
  66307. else {
  66308. if (targetTexture) {
  66309. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  66310. pp._outputTexture = targetTexture;
  66311. }
  66312. else {
  66313. engine.restoreDefaultFramebuffer();
  66314. pp._outputTexture = null;
  66315. }
  66316. }
  66317. if (doNotPresent) {
  66318. break;
  66319. }
  66320. var effect = pp.apply();
  66321. if (effect) {
  66322. pp.onBeforeRenderObservable.notifyObservers(effect);
  66323. // VBOs
  66324. this._prepareBuffers();
  66325. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66326. // Draw order
  66327. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66328. pp.onAfterRenderObservable.notifyObservers(effect);
  66329. }
  66330. }
  66331. // Restore states
  66332. engine.setDepthBuffer(true);
  66333. engine.setDepthWrite(true);
  66334. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66335. };
  66336. /**
  66337. * Disposes of the post process manager.
  66338. */
  66339. PostProcessManager.prototype.dispose = function () {
  66340. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66341. if (buffer) {
  66342. buffer.dispose();
  66343. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66344. }
  66345. if (this._indexBuffer) {
  66346. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66347. this._indexBuffer = null;
  66348. }
  66349. };
  66350. return PostProcessManager;
  66351. }());
  66352. BABYLON.PostProcessManager = PostProcessManager;
  66353. })(BABYLON || (BABYLON = {}));
  66354. //# sourceMappingURL=babylon.postProcessManager.js.map
  66355. var BABYLON;
  66356. (function (BABYLON) {
  66357. /**
  66358. * PostProcess can be used to apply a shader to a texture after it has been rendered
  66359. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66360. */
  66361. var PostProcess = /** @class */ (function () {
  66362. /**
  66363. * Creates a new instance PostProcess
  66364. * @param name The name of the PostProcess.
  66365. * @param fragmentUrl The url of the fragment shader to be used.
  66366. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  66367. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  66368. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66369. * @param camera The camera to apply the render pass to.
  66370. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66371. * @param engine The engine which the post process will be applied. (default: current engine)
  66372. * @param reusable If the post process can be reused on the same frame. (default: false)
  66373. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  66374. * @param textureType Type of textures used when performing the post process. (default: 0)
  66375. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  66376. * @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
  66377. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  66378. */
  66379. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  66380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  66381. if (defines === void 0) { defines = null; }
  66382. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66383. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  66384. if (blockCompilation === void 0) { blockCompilation = false; }
  66385. this.name = name;
  66386. /**
  66387. * Width of the texture to apply the post process on
  66388. */
  66389. this.width = -1;
  66390. /**
  66391. * Height of the texture to apply the post process on
  66392. */
  66393. this.height = -1;
  66394. /**
  66395. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  66396. */
  66397. this._outputTexture = null;
  66398. /**
  66399. * If the buffer needs to be cleared before applying the post process. (default: true)
  66400. * Should be set to false if shader will overwrite all previous pixels.
  66401. */
  66402. this.autoClear = true;
  66403. /**
  66404. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  66405. */
  66406. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  66407. /**
  66408. * Animations to be used for the post processing
  66409. */
  66410. this.animations = new Array();
  66411. /**
  66412. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  66413. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  66414. */
  66415. this.enablePixelPerfectMode = false;
  66416. /**
  66417. * Force the postprocess to be applied without taking in account viewport
  66418. */
  66419. this.forceFullscreenViewport = true;
  66420. /**
  66421. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  66422. *
  66423. * | Value | Type | Description |
  66424. * | ----- | ----------------------------------- | ----------- |
  66425. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  66426. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  66427. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  66428. *
  66429. */
  66430. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  66431. /**
  66432. * Force textures to be a power of two (default: false)
  66433. */
  66434. this.alwaysForcePOT = false;
  66435. /**
  66436. * Number of sample textures (default: 1)
  66437. */
  66438. this.samples = 1;
  66439. /**
  66440. * Modify the scale of the post process to be the same as the viewport (default: false)
  66441. */
  66442. this.adaptScaleToCurrentViewport = false;
  66443. this._reusable = false;
  66444. /**
  66445. * Smart array of input and output textures for the post process.
  66446. */
  66447. this._textures = new BABYLON.SmartArray(2);
  66448. /**
  66449. * The index in _textures that corresponds to the output texture.
  66450. */
  66451. this._currentRenderTextureInd = 0;
  66452. this._scaleRatio = new BABYLON.Vector2(1, 1);
  66453. this._texelSize = BABYLON.Vector2.Zero();
  66454. // Events
  66455. /**
  66456. * An event triggered when the postprocess is activated.
  66457. */
  66458. this.onActivateObservable = new BABYLON.Observable();
  66459. /**
  66460. * An event triggered when the postprocess changes its size.
  66461. */
  66462. this.onSizeChangedObservable = new BABYLON.Observable();
  66463. /**
  66464. * An event triggered when the postprocess applies its effect.
  66465. */
  66466. this.onApplyObservable = new BABYLON.Observable();
  66467. /**
  66468. * An event triggered before rendering the postprocess
  66469. */
  66470. this.onBeforeRenderObservable = new BABYLON.Observable();
  66471. /**
  66472. * An event triggered after rendering the postprocess
  66473. */
  66474. this.onAfterRenderObservable = new BABYLON.Observable();
  66475. if (camera != null) {
  66476. this._camera = camera;
  66477. this._scene = camera.getScene();
  66478. camera.attachPostProcess(this);
  66479. this._engine = this._scene.getEngine();
  66480. this._scene.postProcesses.push(this);
  66481. }
  66482. else if (engine) {
  66483. this._engine = engine;
  66484. this._engine.postProcesses.push(this);
  66485. }
  66486. this._options = options;
  66487. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  66488. this._reusable = reusable || false;
  66489. this._textureType = textureType;
  66490. this._samplers = samplers || [];
  66491. this._samplers.push("textureSampler");
  66492. this._fragmentUrl = fragmentUrl;
  66493. this._vertexUrl = vertexUrl;
  66494. this._parameters = parameters || [];
  66495. this._parameters.push("scale");
  66496. this._indexParameters = indexParameters;
  66497. if (!blockCompilation) {
  66498. this.updateEffect(defines);
  66499. }
  66500. }
  66501. Object.defineProperty(PostProcess.prototype, "onActivate", {
  66502. /**
  66503. * A function that is added to the onActivateObservable
  66504. */
  66505. set: function (callback) {
  66506. if (this._onActivateObserver) {
  66507. this.onActivateObservable.remove(this._onActivateObserver);
  66508. }
  66509. if (callback) {
  66510. this._onActivateObserver = this.onActivateObservable.add(callback);
  66511. }
  66512. },
  66513. enumerable: true,
  66514. configurable: true
  66515. });
  66516. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  66517. /**
  66518. * A function that is added to the onSizeChangedObservable
  66519. */
  66520. set: function (callback) {
  66521. if (this._onSizeChangedObserver) {
  66522. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  66523. }
  66524. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  66525. },
  66526. enumerable: true,
  66527. configurable: true
  66528. });
  66529. Object.defineProperty(PostProcess.prototype, "onApply", {
  66530. /**
  66531. * A function that is added to the onApplyObservable
  66532. */
  66533. set: function (callback) {
  66534. if (this._onApplyObserver) {
  66535. this.onApplyObservable.remove(this._onApplyObserver);
  66536. }
  66537. this._onApplyObserver = this.onApplyObservable.add(callback);
  66538. },
  66539. enumerable: true,
  66540. configurable: true
  66541. });
  66542. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  66543. /**
  66544. * A function that is added to the onBeforeRenderObservable
  66545. */
  66546. set: function (callback) {
  66547. if (this._onBeforeRenderObserver) {
  66548. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66549. }
  66550. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66551. },
  66552. enumerable: true,
  66553. configurable: true
  66554. });
  66555. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  66556. /**
  66557. * A function that is added to the onAfterRenderObservable
  66558. */
  66559. set: function (callback) {
  66560. if (this._onAfterRenderObserver) {
  66561. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66562. }
  66563. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66564. },
  66565. enumerable: true,
  66566. configurable: true
  66567. });
  66568. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  66569. /**
  66570. * 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
  66571. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  66572. */
  66573. get: function () {
  66574. return this._textures.data[this._currentRenderTextureInd];
  66575. },
  66576. set: function (value) {
  66577. this._forcedOutputTexture = value;
  66578. },
  66579. enumerable: true,
  66580. configurable: true
  66581. });
  66582. /**
  66583. * Gets the camera which post process is applied to.
  66584. * @returns The camera the post process is applied to.
  66585. */
  66586. PostProcess.prototype.getCamera = function () {
  66587. return this._camera;
  66588. };
  66589. Object.defineProperty(PostProcess.prototype, "texelSize", {
  66590. /**
  66591. * Gets the texel size of the postprocess.
  66592. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  66593. */
  66594. get: function () {
  66595. if (this._shareOutputWithPostProcess) {
  66596. return this._shareOutputWithPostProcess.texelSize;
  66597. }
  66598. if (this._forcedOutputTexture) {
  66599. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  66600. }
  66601. return this._texelSize;
  66602. },
  66603. enumerable: true,
  66604. configurable: true
  66605. });
  66606. /**
  66607. * Gets the engine which this post process belongs to.
  66608. * @returns The engine the post process was enabled with.
  66609. */
  66610. PostProcess.prototype.getEngine = function () {
  66611. return this._engine;
  66612. };
  66613. /**
  66614. * The effect that is created when initializing the post process.
  66615. * @returns The created effect corrisponding the the postprocess.
  66616. */
  66617. PostProcess.prototype.getEffect = function () {
  66618. return this._effect;
  66619. };
  66620. /**
  66621. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  66622. * @param postProcess The post process to share the output with.
  66623. * @returns This post process.
  66624. */
  66625. PostProcess.prototype.shareOutputWith = function (postProcess) {
  66626. this._disposeTextures();
  66627. this._shareOutputWithPostProcess = postProcess;
  66628. return this;
  66629. };
  66630. /**
  66631. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  66632. * This should be called if the post process that shares output with this post process is disabled/disposed.
  66633. */
  66634. PostProcess.prototype.useOwnOutput = function () {
  66635. if (this._textures.length == 0) {
  66636. this._textures = new BABYLON.SmartArray(2);
  66637. }
  66638. this._shareOutputWithPostProcess = null;
  66639. };
  66640. /**
  66641. * Updates the effect with the current post process compile time values and recompiles the shader.
  66642. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  66643. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  66644. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  66645. * @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
  66646. * @param onCompiled Called when the shader has been compiled.
  66647. * @param onError Called if there is an error when compiling a shader.
  66648. */
  66649. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  66650. if (defines === void 0) { defines = null; }
  66651. if (uniforms === void 0) { uniforms = null; }
  66652. if (samplers === void 0) { samplers = null; }
  66653. 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);
  66654. };
  66655. /**
  66656. * The post process is reusable if it can be used multiple times within one frame.
  66657. * @returns If the post process is reusable
  66658. */
  66659. PostProcess.prototype.isReusable = function () {
  66660. return this._reusable;
  66661. };
  66662. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  66663. PostProcess.prototype.markTextureDirty = function () {
  66664. this.width = -1;
  66665. };
  66666. /**
  66667. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  66668. * 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.
  66669. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  66670. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  66671. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  66672. * @returns The target texture that was bound to be written to.
  66673. */
  66674. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  66675. var _this = this;
  66676. if (sourceTexture === void 0) { sourceTexture = null; }
  66677. camera = camera || this._camera;
  66678. var scene = camera.getScene();
  66679. var engine = scene.getEngine();
  66680. var maxSize = engine.getCaps().maxTextureSize;
  66681. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  66682. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  66683. // 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
  66684. var webVRCamera = camera.parent;
  66685. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  66686. requiredWidth /= 2;
  66687. }
  66688. var desiredWidth = (this._options.width || requiredWidth);
  66689. var desiredHeight = this._options.height || requiredHeight;
  66690. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  66691. if (this.adaptScaleToCurrentViewport) {
  66692. var currentViewport = engine.currentViewport;
  66693. if (currentViewport) {
  66694. desiredWidth *= currentViewport.width;
  66695. desiredHeight *= currentViewport.height;
  66696. }
  66697. }
  66698. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  66699. if (!this._options.width) {
  66700. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  66701. }
  66702. if (!this._options.height) {
  66703. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  66704. }
  66705. }
  66706. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  66707. if (this._textures.length > 0) {
  66708. for (var i = 0; i < this._textures.length; i++) {
  66709. this._engine._releaseTexture(this._textures.data[i]);
  66710. }
  66711. this._textures.reset();
  66712. }
  66713. this.width = desiredWidth;
  66714. this.height = desiredHeight;
  66715. var textureSize = { width: this.width, height: this.height };
  66716. var textureOptions = {
  66717. generateMipMaps: false,
  66718. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  66719. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  66720. samplingMode: this.renderTargetSamplingMode,
  66721. type: this._textureType
  66722. };
  66723. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66724. if (this._reusable) {
  66725. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66726. }
  66727. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  66728. this.onSizeChangedObservable.notifyObservers(this);
  66729. }
  66730. this._textures.forEach(function (texture) {
  66731. if (texture.samples !== _this.samples) {
  66732. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  66733. }
  66734. });
  66735. }
  66736. var target;
  66737. if (this._shareOutputWithPostProcess) {
  66738. target = this._shareOutputWithPostProcess.inputTexture;
  66739. }
  66740. else if (this._forcedOutputTexture) {
  66741. target = this._forcedOutputTexture;
  66742. this.width = this._forcedOutputTexture.width;
  66743. this.height = this._forcedOutputTexture.height;
  66744. }
  66745. else {
  66746. target = this.inputTexture;
  66747. }
  66748. // Bind the input of this post process to be used as the output of the previous post process.
  66749. if (this.enablePixelPerfectMode) {
  66750. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  66751. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  66752. }
  66753. else {
  66754. this._scaleRatio.copyFromFloats(1, 1);
  66755. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  66756. }
  66757. this.onActivateObservable.notifyObservers(camera);
  66758. // Clear
  66759. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  66760. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  66761. }
  66762. if (this._reusable) {
  66763. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  66764. }
  66765. return target;
  66766. };
  66767. Object.defineProperty(PostProcess.prototype, "isSupported", {
  66768. /**
  66769. * If the post process is supported.
  66770. */
  66771. get: function () {
  66772. return this._effect.isSupported;
  66773. },
  66774. enumerable: true,
  66775. configurable: true
  66776. });
  66777. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  66778. /**
  66779. * The aspect ratio of the output texture.
  66780. */
  66781. get: function () {
  66782. if (this._shareOutputWithPostProcess) {
  66783. return this._shareOutputWithPostProcess.aspectRatio;
  66784. }
  66785. if (this._forcedOutputTexture) {
  66786. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  66787. }
  66788. return this.width / this.height;
  66789. },
  66790. enumerable: true,
  66791. configurable: true
  66792. });
  66793. /**
  66794. * Get a value indicating if the post-process is ready to be used
  66795. * @returns true if the post-process is ready (shader is compiled)
  66796. */
  66797. PostProcess.prototype.isReady = function () {
  66798. return this._effect && this._effect.isReady();
  66799. };
  66800. /**
  66801. * Binds all textures and uniforms to the shader, this will be run on every pass.
  66802. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  66803. */
  66804. PostProcess.prototype.apply = function () {
  66805. // Check
  66806. if (!this._effect || !this._effect.isReady())
  66807. return null;
  66808. // States
  66809. this._engine.enableEffect(this._effect);
  66810. this._engine.setState(false);
  66811. this._engine.setDepthBuffer(false);
  66812. this._engine.setDepthWrite(false);
  66813. // Alpha
  66814. this._engine.setAlphaMode(this.alphaMode);
  66815. if (this.alphaConstants) {
  66816. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  66817. }
  66818. // Bind the output texture of the preivous post process as the input to this post process.
  66819. var source;
  66820. if (this._shareOutputWithPostProcess) {
  66821. source = this._shareOutputWithPostProcess.inputTexture;
  66822. }
  66823. else if (this._forcedOutputTexture) {
  66824. source = this._forcedOutputTexture;
  66825. }
  66826. else {
  66827. source = this.inputTexture;
  66828. }
  66829. this._effect._bindTexture("textureSampler", source);
  66830. // Parameters
  66831. this._effect.setVector2("scale", this._scaleRatio);
  66832. this.onApplyObservable.notifyObservers(this._effect);
  66833. return this._effect;
  66834. };
  66835. PostProcess.prototype._disposeTextures = function () {
  66836. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66837. return;
  66838. }
  66839. if (this._textures.length > 0) {
  66840. for (var i = 0; i < this._textures.length; i++) {
  66841. this._engine._releaseTexture(this._textures.data[i]);
  66842. }
  66843. }
  66844. this._textures.dispose();
  66845. };
  66846. /**
  66847. * Disposes the post process.
  66848. * @param camera The camera to dispose the post process on.
  66849. */
  66850. PostProcess.prototype.dispose = function (camera) {
  66851. camera = camera || this._camera;
  66852. this._disposeTextures();
  66853. if (this._scene) {
  66854. var index_1 = this._scene.postProcesses.indexOf(this);
  66855. if (index_1 !== -1) {
  66856. this._scene.postProcesses.splice(index_1, 1);
  66857. }
  66858. }
  66859. else {
  66860. var index_2 = this._engine.postProcesses.indexOf(this);
  66861. if (index_2 !== -1) {
  66862. this._engine.postProcesses.splice(index_2, 1);
  66863. }
  66864. }
  66865. if (!camera) {
  66866. return;
  66867. }
  66868. camera.detachPostProcess(this);
  66869. var index = camera._postProcesses.indexOf(this);
  66870. if (index === 0 && camera._postProcesses.length > 0) {
  66871. var firstPostProcess = this._camera._getFirstPostProcess();
  66872. if (firstPostProcess) {
  66873. firstPostProcess.markTextureDirty();
  66874. }
  66875. }
  66876. this.onActivateObservable.clear();
  66877. this.onAfterRenderObservable.clear();
  66878. this.onApplyObservable.clear();
  66879. this.onBeforeRenderObservable.clear();
  66880. this.onSizeChangedObservable.clear();
  66881. };
  66882. return PostProcess;
  66883. }());
  66884. BABYLON.PostProcess = PostProcess;
  66885. })(BABYLON || (BABYLON = {}));
  66886. //# sourceMappingURL=babylon.postProcess.js.map
  66887. var BABYLON;
  66888. (function (BABYLON) {
  66889. var PassPostProcess = /** @class */ (function (_super) {
  66890. __extends(PassPostProcess, _super);
  66891. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66892. if (camera === void 0) { camera = null; }
  66893. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66894. if (blockCompilation === void 0) { blockCompilation = false; }
  66895. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66896. }
  66897. return PassPostProcess;
  66898. }(BABYLON.PostProcess));
  66899. BABYLON.PassPostProcess = PassPostProcess;
  66900. })(BABYLON || (BABYLON = {}));
  66901. //# sourceMappingURL=babylon.passPostProcess.js.map
  66902. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66903. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66904. s = arguments[i];
  66905. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66906. t[p] = s[p];
  66907. }
  66908. return t;
  66909. };
  66910. var BABYLON;
  66911. (function (BABYLON) {
  66912. /**
  66913. * Default implementation IShadowGenerator.
  66914. * This is the main object responsible of generating shadows in the framework.
  66915. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66916. */
  66917. var ShadowGenerator = /** @class */ (function () {
  66918. /**
  66919. * Creates a ShadowGenerator object.
  66920. * A ShadowGenerator is the required tool to use the shadows.
  66921. * Each light casting shadows needs to use its own ShadowGenerator.
  66922. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66923. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66924. * @param light The light object generating the shadows.
  66925. * @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.
  66926. */
  66927. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66928. this._bias = 0.00005;
  66929. this._normalBias = 0;
  66930. this._blurBoxOffset = 1;
  66931. this._blurScale = 2;
  66932. this._blurKernel = 1;
  66933. this._useKernelBlur = false;
  66934. this._filter = ShadowGenerator.FILTER_NONE;
  66935. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66936. this._contactHardeningLightSizeUVRatio = 0.1;
  66937. this._darkness = 0;
  66938. this._transparencyShadow = false;
  66939. /**
  66940. * Controls the extent to which the shadows fade out at the edge of the frustum
  66941. * Used only by directionals and spots
  66942. */
  66943. this.frustumEdgeFalloff = 0;
  66944. /**
  66945. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66946. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66947. * It might on the other hand introduce peter panning.
  66948. */
  66949. this.forceBackFacesOnly = false;
  66950. this._lightDirection = BABYLON.Vector3.Zero();
  66951. this._viewMatrix = BABYLON.Matrix.Zero();
  66952. this._projectionMatrix = BABYLON.Matrix.Zero();
  66953. this._transformMatrix = BABYLON.Matrix.Zero();
  66954. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66955. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66956. this._currentFaceIndex = 0;
  66957. this._currentFaceIndexCache = 0;
  66958. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66959. this._mapSize = mapSize;
  66960. this._light = light;
  66961. this._scene = light.getScene();
  66962. light._shadowGenerator = this;
  66963. // Texture type fallback from float to int if not supported.
  66964. var caps = this._scene.getEngine().getCaps();
  66965. if (!useFullFloatFirst) {
  66966. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66967. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66968. }
  66969. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66970. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66971. }
  66972. else {
  66973. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66974. }
  66975. }
  66976. else {
  66977. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66978. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66979. }
  66980. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66981. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66982. }
  66983. else {
  66984. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66985. }
  66986. }
  66987. this._initializeGenerator();
  66988. this._applyFilterValues();
  66989. }
  66990. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66991. /**
  66992. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66993. */
  66994. get: function () {
  66995. return this._bias;
  66996. },
  66997. /**
  66998. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66999. */
  67000. set: function (bias) {
  67001. this._bias = bias;
  67002. },
  67003. enumerable: true,
  67004. configurable: true
  67005. });
  67006. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67007. /**
  67008. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67009. */
  67010. get: function () {
  67011. return this._normalBias;
  67012. },
  67013. /**
  67014. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67015. */
  67016. set: function (normalBias) {
  67017. this._normalBias = normalBias;
  67018. },
  67019. enumerable: true,
  67020. configurable: true
  67021. });
  67022. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67023. /**
  67024. * Gets the blur box offset: offset applied during the blur pass.
  67025. * Only usefull if useKernelBlur = false
  67026. */
  67027. get: function () {
  67028. return this._blurBoxOffset;
  67029. },
  67030. /**
  67031. * Sets the blur box offset: offset applied during the blur pass.
  67032. * Only usefull if useKernelBlur = false
  67033. */
  67034. set: function (value) {
  67035. if (this._blurBoxOffset === value) {
  67036. return;
  67037. }
  67038. this._blurBoxOffset = value;
  67039. this._disposeBlurPostProcesses();
  67040. },
  67041. enumerable: true,
  67042. configurable: true
  67043. });
  67044. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67045. /**
  67046. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67047. * 2 means half of the size.
  67048. */
  67049. get: function () {
  67050. return this._blurScale;
  67051. },
  67052. /**
  67053. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67054. * 2 means half of the size.
  67055. */
  67056. set: function (value) {
  67057. if (this._blurScale === value) {
  67058. return;
  67059. }
  67060. this._blurScale = value;
  67061. this._disposeBlurPostProcesses();
  67062. },
  67063. enumerable: true,
  67064. configurable: true
  67065. });
  67066. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67067. /**
  67068. * Gets the blur kernel: kernel size of the blur pass.
  67069. * Only usefull if useKernelBlur = true
  67070. */
  67071. get: function () {
  67072. return this._blurKernel;
  67073. },
  67074. /**
  67075. * Sets the blur kernel: kernel size of the blur pass.
  67076. * Only usefull if useKernelBlur = true
  67077. */
  67078. set: function (value) {
  67079. if (this._blurKernel === value) {
  67080. return;
  67081. }
  67082. this._blurKernel = value;
  67083. this._disposeBlurPostProcesses();
  67084. },
  67085. enumerable: true,
  67086. configurable: true
  67087. });
  67088. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67089. /**
  67090. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67091. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67092. */
  67093. get: function () {
  67094. return this._useKernelBlur;
  67095. },
  67096. /**
  67097. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67098. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67099. */
  67100. set: function (value) {
  67101. if (this._useKernelBlur === value) {
  67102. return;
  67103. }
  67104. this._useKernelBlur = value;
  67105. this._disposeBlurPostProcesses();
  67106. },
  67107. enumerable: true,
  67108. configurable: true
  67109. });
  67110. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  67111. /**
  67112. * Gets the depth scale used in ESM mode.
  67113. */
  67114. get: function () {
  67115. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  67116. },
  67117. /**
  67118. * Sets the depth scale used in ESM mode.
  67119. * This can override the scale stored on the light.
  67120. */
  67121. set: function (value) {
  67122. this._depthScale = value;
  67123. },
  67124. enumerable: true,
  67125. configurable: true
  67126. });
  67127. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  67128. /**
  67129. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  67130. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67131. */
  67132. get: function () {
  67133. return this._filter;
  67134. },
  67135. /**
  67136. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  67137. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67138. */
  67139. set: function (value) {
  67140. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  67141. if (this._light.needCube()) {
  67142. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67143. this.useExponentialShadowMap = true;
  67144. return;
  67145. }
  67146. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67147. this.useCloseExponentialShadowMap = true;
  67148. return;
  67149. }
  67150. // PCF on cubemap would also be expensive
  67151. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67152. this.usePoissonSampling = true;
  67153. return;
  67154. }
  67155. }
  67156. // Weblg1 fallback for PCF.
  67157. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67158. if (this._scene.getEngine().webGLVersion === 1) {
  67159. this.usePoissonSampling = true;
  67160. return;
  67161. }
  67162. }
  67163. if (this._filter === value) {
  67164. return;
  67165. }
  67166. this._filter = value;
  67167. this._disposeBlurPostProcesses();
  67168. this._applyFilterValues();
  67169. this._light._markMeshesAsLightDirty();
  67170. },
  67171. enumerable: true,
  67172. configurable: true
  67173. });
  67174. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  67175. /**
  67176. * Gets if the current filter is set to Poisson Sampling.
  67177. */
  67178. get: function () {
  67179. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  67180. },
  67181. /**
  67182. * Sets the current filter to Poisson Sampling.
  67183. */
  67184. set: function (value) {
  67185. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  67186. return;
  67187. }
  67188. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  67189. },
  67190. enumerable: true,
  67191. configurable: true
  67192. });
  67193. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  67194. /**
  67195. * Gets if the current filter is set to VSM.
  67196. * DEPRECATED. Should use useExponentialShadowMap instead.
  67197. */
  67198. get: function () {
  67199. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67200. return this.useExponentialShadowMap;
  67201. },
  67202. /**
  67203. * Sets the current filter is to VSM.
  67204. * DEPRECATED. Should use useExponentialShadowMap instead.
  67205. */
  67206. set: function (value) {
  67207. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67208. this.useExponentialShadowMap = value;
  67209. },
  67210. enumerable: true,
  67211. configurable: true
  67212. });
  67213. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  67214. /**
  67215. * Gets if the current filter is set to blurred VSM.
  67216. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67217. */
  67218. get: function () {
  67219. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67220. return this.useBlurExponentialShadowMap;
  67221. },
  67222. /**
  67223. * Sets the current filter is to blurred VSM.
  67224. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67225. */
  67226. set: function (value) {
  67227. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67228. this.useBlurExponentialShadowMap = value;
  67229. },
  67230. enumerable: true,
  67231. configurable: true
  67232. });
  67233. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  67234. /**
  67235. * Gets if the current filter is set to ESM.
  67236. */
  67237. get: function () {
  67238. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  67239. },
  67240. /**
  67241. * Sets the current filter is to ESM.
  67242. */
  67243. set: function (value) {
  67244. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  67245. return;
  67246. }
  67247. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67248. },
  67249. enumerable: true,
  67250. configurable: true
  67251. });
  67252. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  67253. /**
  67254. * Gets if the current filter is set to filtered ESM.
  67255. */
  67256. get: function () {
  67257. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  67258. },
  67259. /**
  67260. * Gets if the current filter is set to filtered ESM.
  67261. */
  67262. set: function (value) {
  67263. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67264. return;
  67265. }
  67266. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67267. },
  67268. enumerable: true,
  67269. configurable: true
  67270. });
  67271. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  67272. /**
  67273. * Gets if the current filter is set to "close ESM" (using the inverse of the
  67274. * exponential to prevent steep falloff artifacts).
  67275. */
  67276. get: function () {
  67277. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  67278. },
  67279. /**
  67280. * Sets the current filter to "close ESM" (using the inverse of the
  67281. * exponential to prevent steep falloff artifacts).
  67282. */
  67283. set: function (value) {
  67284. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  67285. return;
  67286. }
  67287. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67288. },
  67289. enumerable: true,
  67290. configurable: true
  67291. });
  67292. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  67293. /**
  67294. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  67295. * exponential to prevent steep falloff artifacts).
  67296. */
  67297. get: function () {
  67298. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  67299. },
  67300. /**
  67301. * Sets the current filter to filtered "close ESM" (using the inverse of the
  67302. * exponential to prevent steep falloff artifacts).
  67303. */
  67304. set: function (value) {
  67305. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67306. return;
  67307. }
  67308. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67309. },
  67310. enumerable: true,
  67311. configurable: true
  67312. });
  67313. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  67314. /**
  67315. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  67316. */
  67317. get: function () {
  67318. return this.filter === ShadowGenerator.FILTER_PCF;
  67319. },
  67320. /**
  67321. * Sets the current filter to "PCF" (percentage closer filtering).
  67322. */
  67323. set: function (value) {
  67324. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  67325. return;
  67326. }
  67327. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  67328. },
  67329. enumerable: true,
  67330. configurable: true
  67331. });
  67332. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  67333. /**
  67334. * Gets the PCF or PCSS Quality.
  67335. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67336. */
  67337. get: function () {
  67338. return this._filteringQuality;
  67339. },
  67340. /**
  67341. * Sets the PCF or PCSS Quality.
  67342. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67343. */
  67344. set: function (filteringQuality) {
  67345. this._filteringQuality = filteringQuality;
  67346. },
  67347. enumerable: true,
  67348. configurable: true
  67349. });
  67350. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  67351. /**
  67352. * Gets if the current filter is set to "PCSS" (contact hardening).
  67353. */
  67354. get: function () {
  67355. return this.filter === ShadowGenerator.FILTER_PCSS;
  67356. },
  67357. /**
  67358. * Sets the current filter to "PCSS" (contact hardening).
  67359. */
  67360. set: function (value) {
  67361. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  67362. return;
  67363. }
  67364. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  67365. },
  67366. enumerable: true,
  67367. configurable: true
  67368. });
  67369. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  67370. /**
  67371. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67372. * Using a ratio helps keeping shape stability independently of the map size.
  67373. *
  67374. * It does not account for the light projection as it was having too much
  67375. * instability during the light setup or during light position changes.
  67376. *
  67377. * Only valid if useContactHardeningShadow is true.
  67378. */
  67379. get: function () {
  67380. return this._contactHardeningLightSizeUVRatio;
  67381. },
  67382. /**
  67383. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67384. * Using a ratio helps keeping shape stability independently of the map size.
  67385. *
  67386. * It does not account for the light projection as it was having too much
  67387. * instability during the light setup or during light position changes.
  67388. *
  67389. * Only valid if useContactHardeningShadow is true.
  67390. */
  67391. set: function (contactHardeningLightSizeUVRatio) {
  67392. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  67393. },
  67394. enumerable: true,
  67395. configurable: true
  67396. });
  67397. /**
  67398. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  67399. * 0 means strongest and 1 would means no shadow.
  67400. * @returns the darkness.
  67401. */
  67402. ShadowGenerator.prototype.getDarkness = function () {
  67403. return this._darkness;
  67404. };
  67405. /**
  67406. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  67407. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  67408. * @returns the shadow generator allowing fluent coding.
  67409. */
  67410. ShadowGenerator.prototype.setDarkness = function (darkness) {
  67411. if (darkness >= 1.0)
  67412. this._darkness = 1.0;
  67413. else if (darkness <= 0.0)
  67414. this._darkness = 0.0;
  67415. else
  67416. this._darkness = darkness;
  67417. return this;
  67418. };
  67419. /**
  67420. * Sets the ability to have transparent shadow (boolean).
  67421. * @param transparent True if transparent else False
  67422. * @returns the shadow generator allowing fluent coding
  67423. */
  67424. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  67425. this._transparencyShadow = transparent;
  67426. return this;
  67427. };
  67428. /**
  67429. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  67430. * @returns The render target texture if present otherwise, null
  67431. */
  67432. ShadowGenerator.prototype.getShadowMap = function () {
  67433. return this._shadowMap;
  67434. };
  67435. /**
  67436. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  67437. * @returns The render target texture if the shadow map is present otherwise, null
  67438. */
  67439. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  67440. if (this._shadowMap2) {
  67441. return this._shadowMap2;
  67442. }
  67443. return this._shadowMap;
  67444. };
  67445. /**
  67446. * Helper function to add a mesh and its descendants to the list of shadow casters.
  67447. * @param mesh Mesh to add
  67448. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  67449. * @returns the Shadow Generator itself
  67450. */
  67451. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  67452. if (includeDescendants === void 0) { includeDescendants = true; }
  67453. if (!this._shadowMap) {
  67454. return this;
  67455. }
  67456. if (!this._shadowMap.renderList) {
  67457. this._shadowMap.renderList = [];
  67458. }
  67459. this._shadowMap.renderList.push(mesh);
  67460. if (includeDescendants) {
  67461. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  67462. }
  67463. return this;
  67464. var _a;
  67465. };
  67466. /**
  67467. * Helper function to remove a mesh and its descendants from the list of shadow casters
  67468. * @param mesh Mesh to remove
  67469. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  67470. * @returns the Shadow Generator itself
  67471. */
  67472. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  67473. if (includeDescendants === void 0) { includeDescendants = true; }
  67474. if (!this._shadowMap || !this._shadowMap.renderList) {
  67475. return this;
  67476. }
  67477. var index = this._shadowMap.renderList.indexOf(mesh);
  67478. if (index !== -1) {
  67479. this._shadowMap.renderList.splice(index, 1);
  67480. }
  67481. if (includeDescendants) {
  67482. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  67483. var child = _a[_i];
  67484. this.removeShadowCaster(child);
  67485. }
  67486. }
  67487. return this;
  67488. };
  67489. /**
  67490. * Returns the associated light object.
  67491. * @returns the light generating the shadow
  67492. */
  67493. ShadowGenerator.prototype.getLight = function () {
  67494. return this._light;
  67495. };
  67496. ShadowGenerator.prototype._initializeGenerator = function () {
  67497. this._light._markMeshesAsLightDirty();
  67498. this._initializeShadowMap();
  67499. };
  67500. ShadowGenerator.prototype._initializeShadowMap = function () {
  67501. var _this = this;
  67502. // Render target
  67503. var engine = this._scene.getEngine();
  67504. if (engine.webGLVersion > 1) {
  67505. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  67506. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  67507. }
  67508. else {
  67509. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  67510. }
  67511. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67512. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67513. this._shadowMap.anisotropicFilteringLevel = 1;
  67514. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67515. this._shadowMap.renderParticles = false;
  67516. this._shadowMap.ignoreCameraViewport = true;
  67517. // Record Face Index before render.
  67518. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  67519. _this._currentFaceIndex = faceIndex;
  67520. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67521. engine.setColorWrite(false);
  67522. }
  67523. });
  67524. // Custom render function.
  67525. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  67526. // Blur if required afer render.
  67527. this._shadowMap.onAfterUnbindObservable.add(function () {
  67528. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67529. engine.setColorWrite(true);
  67530. }
  67531. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  67532. return;
  67533. }
  67534. var shadowMap = _this.getShadowMapForRendering();
  67535. if (shadowMap) {
  67536. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  67537. }
  67538. });
  67539. // Clear according to the chosen filter.
  67540. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  67541. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67542. this._shadowMap.onClearObservable.add(function (engine) {
  67543. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67544. engine.clear(clearOne, false, true, false);
  67545. }
  67546. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  67547. engine.clear(clearZero, true, true, false);
  67548. }
  67549. else {
  67550. engine.clear(clearOne, true, true, false);
  67551. }
  67552. });
  67553. };
  67554. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  67555. var _this = this;
  67556. var engine = this._scene.getEngine();
  67557. var targetSize = this._mapSize / this.blurScale;
  67558. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  67559. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  67560. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67561. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67562. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67563. }
  67564. if (this.useKernelBlur) {
  67565. 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);
  67566. this._kernelBlurXPostprocess.width = targetSize;
  67567. this._kernelBlurXPostprocess.height = targetSize;
  67568. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  67569. effect.setTexture("textureSampler", _this._shadowMap);
  67570. });
  67571. 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);
  67572. this._kernelBlurXPostprocess.autoClear = false;
  67573. this._kernelBlurYPostprocess.autoClear = false;
  67574. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67575. this._kernelBlurXPostprocess.packedFloat = true;
  67576. this._kernelBlurYPostprocess.packedFloat = true;
  67577. }
  67578. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  67579. }
  67580. else {
  67581. 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);
  67582. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  67583. effect.setFloat2("screenSize", targetSize, targetSize);
  67584. effect.setTexture("textureSampler", _this._shadowMap);
  67585. });
  67586. this._boxBlurPostprocess.autoClear = false;
  67587. this._blurPostProcesses = [this._boxBlurPostprocess];
  67588. }
  67589. };
  67590. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67591. var index;
  67592. var engine = this._scene.getEngine();
  67593. if (depthOnlySubMeshes.length) {
  67594. engine.setColorWrite(false);
  67595. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67596. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  67597. }
  67598. engine.setColorWrite(true);
  67599. }
  67600. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67601. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  67602. }
  67603. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67604. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  67605. }
  67606. if (this._transparencyShadow) {
  67607. for (index = 0; index < transparentSubMeshes.length; index++) {
  67608. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  67609. }
  67610. }
  67611. };
  67612. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  67613. var _this = this;
  67614. var mesh = subMesh.getRenderingMesh();
  67615. var scene = this._scene;
  67616. var engine = scene.getEngine();
  67617. var material = subMesh.getMaterial();
  67618. if (!material) {
  67619. return;
  67620. }
  67621. // Culling
  67622. engine.setState(material.backFaceCulling);
  67623. // Managing instances
  67624. var batch = mesh._getInstancesRenderList(subMesh._id);
  67625. if (batch.mustReturn) {
  67626. return;
  67627. }
  67628. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67629. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  67630. engine.enableEffect(this._effect);
  67631. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  67632. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  67633. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  67634. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67635. this._effect.setVector3("lightData", this._cachedDirection);
  67636. }
  67637. else {
  67638. this._effect.setVector3("lightData", this._cachedPosition);
  67639. }
  67640. if (scene.activeCamera) {
  67641. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  67642. }
  67643. // Alpha test
  67644. if (material && material.needAlphaTesting()) {
  67645. var alphaTexture = material.getAlphaTestTexture();
  67646. if (alphaTexture) {
  67647. this._effect.setTexture("diffuseSampler", alphaTexture);
  67648. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  67649. }
  67650. }
  67651. // Bones
  67652. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67653. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  67654. }
  67655. // Morph targets
  67656. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  67657. if (this.forceBackFacesOnly) {
  67658. engine.setState(true, 0, false, true);
  67659. }
  67660. // Draw
  67661. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67662. if (this.forceBackFacesOnly) {
  67663. engine.setState(true, 0, false, false);
  67664. }
  67665. }
  67666. else {
  67667. // Need to reset refresh rate of the shadowMap
  67668. if (this._shadowMap) {
  67669. this._shadowMap.resetRefreshCounter();
  67670. }
  67671. }
  67672. };
  67673. ShadowGenerator.prototype._applyFilterValues = function () {
  67674. if (!this._shadowMap) {
  67675. return;
  67676. }
  67677. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  67678. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67679. }
  67680. else {
  67681. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67682. }
  67683. };
  67684. /**
  67685. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67686. * @param onCompiled Callback triggered at the and of the effects compilation
  67687. * @param options Sets of optional options forcing the compilation with different modes
  67688. */
  67689. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  67690. var _this = this;
  67691. var localOptions = __assign({ useInstances: false }, options);
  67692. var shadowMap = this.getShadowMap();
  67693. if (!shadowMap) {
  67694. if (onCompiled) {
  67695. onCompiled(this);
  67696. }
  67697. return;
  67698. }
  67699. var renderList = shadowMap.renderList;
  67700. if (!renderList) {
  67701. if (onCompiled) {
  67702. onCompiled(this);
  67703. }
  67704. return;
  67705. }
  67706. var subMeshes = new Array();
  67707. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  67708. var mesh = renderList_1[_i];
  67709. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  67710. }
  67711. if (subMeshes.length === 0) {
  67712. if (onCompiled) {
  67713. onCompiled(this);
  67714. }
  67715. return;
  67716. }
  67717. var currentIndex = 0;
  67718. var checkReady = function () {
  67719. if (!_this._scene || !_this._scene.getEngine()) {
  67720. return;
  67721. }
  67722. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  67723. currentIndex++;
  67724. if (currentIndex >= subMeshes.length) {
  67725. if (onCompiled) {
  67726. onCompiled(_this);
  67727. }
  67728. return;
  67729. }
  67730. }
  67731. setTimeout(checkReady, 16);
  67732. };
  67733. checkReady();
  67734. };
  67735. /**
  67736. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67737. * @param options Sets of optional options forcing the compilation with different modes
  67738. * @returns A promise that resolves when the compilation completes
  67739. */
  67740. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  67741. var _this = this;
  67742. return new Promise(function (resolve) {
  67743. _this.forceCompilation(function () {
  67744. resolve();
  67745. }, options);
  67746. });
  67747. };
  67748. /**
  67749. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  67750. * @param subMesh The submesh we want to render in the shadow map
  67751. * @param useInstances Defines wether will draw in the map using instances
  67752. * @returns true if ready otherwise, false
  67753. */
  67754. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  67755. var defines = [];
  67756. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67757. defines.push("#define FLOAT");
  67758. }
  67759. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67760. defines.push("#define ESM");
  67761. }
  67762. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  67763. defines.push("#define DEPTHTEXTURE");
  67764. }
  67765. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67766. var mesh = subMesh.getMesh();
  67767. var material = subMesh.getMaterial();
  67768. // Normal bias.
  67769. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67770. attribs.push(BABYLON.VertexBuffer.NormalKind);
  67771. defines.push("#define NORMAL");
  67772. if (mesh.nonUniformScaling) {
  67773. defines.push("#define NONUNIFORMSCALING");
  67774. }
  67775. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67776. defines.push("#define DIRECTIONINLIGHTDATA");
  67777. }
  67778. }
  67779. // Alpha test
  67780. if (material && material.needAlphaTesting()) {
  67781. var alphaTexture = material.getAlphaTestTexture();
  67782. if (alphaTexture) {
  67783. defines.push("#define ALPHATEST");
  67784. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67785. attribs.push(BABYLON.VertexBuffer.UVKind);
  67786. defines.push("#define UV1");
  67787. }
  67788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67789. if (alphaTexture.coordinatesIndex === 1) {
  67790. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67791. defines.push("#define UV2");
  67792. }
  67793. }
  67794. }
  67795. }
  67796. // Bones
  67797. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67798. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67799. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67800. if (mesh.numBoneInfluencers > 4) {
  67801. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67802. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67803. }
  67804. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67805. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67806. }
  67807. else {
  67808. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67809. }
  67810. // Morph targets
  67811. var manager = mesh.morphTargetManager;
  67812. var morphInfluencers = 0;
  67813. if (manager) {
  67814. if (manager.numInfluencers > 0) {
  67815. defines.push("#define MORPHTARGETS");
  67816. morphInfluencers = manager.numInfluencers;
  67817. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  67818. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  67819. }
  67820. }
  67821. // Instances
  67822. if (useInstances) {
  67823. defines.push("#define INSTANCES");
  67824. attribs.push("world0");
  67825. attribs.push("world1");
  67826. attribs.push("world2");
  67827. attribs.push("world3");
  67828. }
  67829. // Get correct effect
  67830. var join = defines.join("\n");
  67831. if (this._cachedDefines !== join) {
  67832. this._cachedDefines = join;
  67833. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67834. }
  67835. if (!this._effect.isReady()) {
  67836. return false;
  67837. }
  67838. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67839. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67840. this._initializeBlurRTTAndPostProcesses();
  67841. }
  67842. }
  67843. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67844. return false;
  67845. }
  67846. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67847. return false;
  67848. }
  67849. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67850. return false;
  67851. }
  67852. return true;
  67853. };
  67854. /**
  67855. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67856. * @param defines Defines of the material we want to update
  67857. * @param lightIndex Index of the light in the enabled light list of the material
  67858. */
  67859. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67860. var scene = this._scene;
  67861. var light = this._light;
  67862. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67863. return;
  67864. }
  67865. defines["SHADOW" + lightIndex] = true;
  67866. if (this.useContactHardeningShadow) {
  67867. defines["SHADOWPCSS" + lightIndex] = true;
  67868. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67869. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67870. }
  67871. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67872. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67873. }
  67874. // else default to high.
  67875. }
  67876. if (this.usePercentageCloserFiltering) {
  67877. defines["SHADOWPCF" + lightIndex] = true;
  67878. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67879. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67880. }
  67881. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67882. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67883. }
  67884. // else default to high.
  67885. }
  67886. else if (this.usePoissonSampling) {
  67887. defines["SHADOWPOISSON" + lightIndex] = true;
  67888. }
  67889. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67890. defines["SHADOWESM" + lightIndex] = true;
  67891. }
  67892. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67893. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67894. }
  67895. if (light.needCube()) {
  67896. defines["SHADOWCUBE" + lightIndex] = true;
  67897. }
  67898. };
  67899. /**
  67900. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67901. * defined in the generator but impacting the effect).
  67902. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67903. * @param effect The effect we are binfing the information for
  67904. */
  67905. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67906. var light = this._light;
  67907. var scene = this._scene;
  67908. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67909. return;
  67910. }
  67911. var camera = scene.activeCamera;
  67912. if (!camera) {
  67913. return;
  67914. }
  67915. var shadowMap = this.getShadowMap();
  67916. if (!shadowMap) {
  67917. return;
  67918. }
  67919. if (!light.needCube()) {
  67920. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67921. }
  67922. // Only PCF uses depth stencil texture.
  67923. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67924. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67925. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67926. }
  67927. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67928. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67929. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67930. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67931. }
  67932. else {
  67933. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67934. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67935. }
  67936. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67937. };
  67938. /**
  67939. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67940. * (eq to shadow prjection matrix * light transform matrix)
  67941. * @returns The transform matrix used to create the shadow map
  67942. */
  67943. ShadowGenerator.prototype.getTransformMatrix = function () {
  67944. var scene = this._scene;
  67945. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67946. return this._transformMatrix;
  67947. }
  67948. this._currentRenderID = scene.getRenderId();
  67949. this._currentFaceIndexCache = this._currentFaceIndex;
  67950. var lightPosition = this._light.position;
  67951. if (this._light.computeTransformedInformation()) {
  67952. lightPosition = this._light.transformedPosition;
  67953. }
  67954. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67955. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67956. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67957. }
  67958. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67959. this._cachedPosition.copyFrom(lightPosition);
  67960. this._cachedDirection.copyFrom(this._lightDirection);
  67961. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67962. var shadowMap = this.getShadowMap();
  67963. if (shadowMap) {
  67964. var renderList = shadowMap.renderList;
  67965. if (renderList) {
  67966. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67967. }
  67968. }
  67969. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67970. }
  67971. return this._transformMatrix;
  67972. };
  67973. /**
  67974. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67975. * Cube and 2D textures for instance.
  67976. */
  67977. ShadowGenerator.prototype.recreateShadowMap = function () {
  67978. var shadowMap = this._shadowMap;
  67979. if (!shadowMap) {
  67980. return;
  67981. }
  67982. // Track render list.
  67983. var renderList = shadowMap.renderList;
  67984. // Clean up existing data.
  67985. this._disposeRTTandPostProcesses();
  67986. // Reinitializes.
  67987. this._initializeGenerator();
  67988. // Reaffect the filter to ensure a correct fallback if necessary.
  67989. this.filter = this.filter;
  67990. // Reaffect the filter.
  67991. this._applyFilterValues();
  67992. // Reaffect Render List.
  67993. this._shadowMap.renderList = renderList;
  67994. };
  67995. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67996. if (this._shadowMap2) {
  67997. this._shadowMap2.dispose();
  67998. this._shadowMap2 = null;
  67999. }
  68000. if (this._boxBlurPostprocess) {
  68001. this._boxBlurPostprocess.dispose();
  68002. this._boxBlurPostprocess = null;
  68003. }
  68004. if (this._kernelBlurXPostprocess) {
  68005. this._kernelBlurXPostprocess.dispose();
  68006. this._kernelBlurXPostprocess = null;
  68007. }
  68008. if (this._kernelBlurYPostprocess) {
  68009. this._kernelBlurYPostprocess.dispose();
  68010. this._kernelBlurYPostprocess = null;
  68011. }
  68012. this._blurPostProcesses = [];
  68013. };
  68014. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68015. if (this._shadowMap) {
  68016. this._shadowMap.dispose();
  68017. this._shadowMap = null;
  68018. }
  68019. this._disposeBlurPostProcesses();
  68020. };
  68021. /**
  68022. * Disposes the ShadowGenerator.
  68023. * Returns nothing.
  68024. */
  68025. ShadowGenerator.prototype.dispose = function () {
  68026. this._disposeRTTandPostProcesses();
  68027. if (this._light) {
  68028. this._light._shadowGenerator = null;
  68029. this._light._markMeshesAsLightDirty();
  68030. }
  68031. };
  68032. /**
  68033. * Serializes the shadow generator setup to a json object.
  68034. * @returns The serialized JSON object
  68035. */
  68036. ShadowGenerator.prototype.serialize = function () {
  68037. var serializationObject = {};
  68038. var shadowMap = this.getShadowMap();
  68039. if (!shadowMap) {
  68040. return serializationObject;
  68041. }
  68042. serializationObject.lightId = this._light.id;
  68043. serializationObject.mapSize = shadowMap.getRenderSize();
  68044. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68045. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68046. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68047. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68048. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68049. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68050. serializationObject.depthScale = this.depthScale;
  68051. serializationObject.darkness = this.getDarkness();
  68052. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68053. serializationObject.blurKernel = this.blurKernel;
  68054. serializationObject.blurScale = this.blurScale;
  68055. serializationObject.useKernelBlur = this.useKernelBlur;
  68056. serializationObject.transparencyShadow = this._transparencyShadow;
  68057. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68058. serializationObject.bias = this.bias;
  68059. serializationObject.normalBias = this.normalBias;
  68060. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68061. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68062. serializationObject.filteringQuality = this.filteringQuality;
  68063. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68064. serializationObject.renderList = [];
  68065. if (shadowMap.renderList) {
  68066. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68067. var mesh = shadowMap.renderList[meshIndex];
  68068. serializationObject.renderList.push(mesh.id);
  68069. }
  68070. }
  68071. return serializationObject;
  68072. };
  68073. /**
  68074. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68075. * @param parsedShadowGenerator The JSON object to parse
  68076. * @param scene The scene to create the shadow map for
  68077. * @returns The parsed shadow generator
  68078. */
  68079. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68080. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68081. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68082. var shadowMap = shadowGenerator.getShadowMap();
  68083. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68084. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68085. meshes.forEach(function (mesh) {
  68086. if (!shadowMap) {
  68087. return;
  68088. }
  68089. if (!shadowMap.renderList) {
  68090. shadowMap.renderList = [];
  68091. }
  68092. shadowMap.renderList.push(mesh);
  68093. });
  68094. }
  68095. if (parsedShadowGenerator.usePoissonSampling) {
  68096. shadowGenerator.usePoissonSampling = true;
  68097. }
  68098. else if (parsedShadowGenerator.useExponentialShadowMap) {
  68099. shadowGenerator.useExponentialShadowMap = true;
  68100. }
  68101. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  68102. shadowGenerator.useBlurExponentialShadowMap = true;
  68103. }
  68104. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  68105. shadowGenerator.useCloseExponentialShadowMap = true;
  68106. }
  68107. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  68108. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  68109. }
  68110. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  68111. shadowGenerator.usePercentageCloserFiltering = true;
  68112. }
  68113. else if (parsedShadowGenerator.useContactHardeningShadow) {
  68114. shadowGenerator.useContactHardeningShadow = true;
  68115. }
  68116. if (parsedShadowGenerator.filteringQuality) {
  68117. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  68118. }
  68119. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  68120. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  68121. }
  68122. // Backward compat
  68123. else if (parsedShadowGenerator.useVarianceShadowMap) {
  68124. shadowGenerator.useExponentialShadowMap = true;
  68125. }
  68126. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  68127. shadowGenerator.useBlurExponentialShadowMap = true;
  68128. }
  68129. if (parsedShadowGenerator.depthScale) {
  68130. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  68131. }
  68132. if (parsedShadowGenerator.blurScale) {
  68133. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  68134. }
  68135. if (parsedShadowGenerator.blurBoxOffset) {
  68136. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  68137. }
  68138. if (parsedShadowGenerator.useKernelBlur) {
  68139. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  68140. }
  68141. if (parsedShadowGenerator.blurKernel) {
  68142. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  68143. }
  68144. if (parsedShadowGenerator.bias !== undefined) {
  68145. shadowGenerator.bias = parsedShadowGenerator.bias;
  68146. }
  68147. if (parsedShadowGenerator.normalBias !== undefined) {
  68148. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  68149. }
  68150. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  68151. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  68152. }
  68153. if (parsedShadowGenerator.darkness) {
  68154. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  68155. }
  68156. if (parsedShadowGenerator.transparencyShadow) {
  68157. shadowGenerator.setTransparencyShadow(true);
  68158. }
  68159. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  68160. return shadowGenerator;
  68161. };
  68162. /**
  68163. * Shadow generator mode None: no filtering applied.
  68164. */
  68165. ShadowGenerator.FILTER_NONE = 0;
  68166. /**
  68167. * Shadow generator mode ESM: Exponential Shadow Mapping.
  68168. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68169. */
  68170. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  68171. /**
  68172. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  68173. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  68174. */
  68175. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  68176. /**
  68177. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  68178. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68179. */
  68180. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  68181. /**
  68182. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  68183. * edge artifacts on steep falloff.
  68184. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68185. */
  68186. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  68187. /**
  68188. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  68189. * edge artifacts on steep falloff.
  68190. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68191. */
  68192. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  68193. /**
  68194. * Shadow generator mode PCF: Percentage Closer Filtering
  68195. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68196. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  68197. */
  68198. ShadowGenerator.FILTER_PCF = 6;
  68199. /**
  68200. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  68201. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68202. * Contact Hardening
  68203. */
  68204. ShadowGenerator.FILTER_PCSS = 7;
  68205. /**
  68206. * Reserved for PCF and PCSS
  68207. * Highest Quality.
  68208. *
  68209. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  68210. *
  68211. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  68212. */
  68213. ShadowGenerator.QUALITY_HIGH = 0;
  68214. /**
  68215. * Reserved for PCF and PCSS
  68216. * Good tradeoff for quality/perf cross devices
  68217. *
  68218. * Execute PCF on a 3*3 kernel.
  68219. *
  68220. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  68221. */
  68222. ShadowGenerator.QUALITY_MEDIUM = 1;
  68223. /**
  68224. * Reserved for PCF and PCSS
  68225. * The lowest quality but the fastest.
  68226. *
  68227. * Execute PCF on a 1*1 kernel.
  68228. *
  68229. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  68230. */
  68231. ShadowGenerator.QUALITY_LOW = 2;
  68232. return ShadowGenerator;
  68233. }());
  68234. BABYLON.ShadowGenerator = ShadowGenerator;
  68235. })(BABYLON || (BABYLON = {}));
  68236. //# sourceMappingURL=babylon.shadowGenerator.js.map
  68237. var BABYLON;
  68238. (function (BABYLON) {
  68239. var DefaultLoadingScreen = /** @class */ (function () {
  68240. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  68241. if (_loadingText === void 0) { _loadingText = ""; }
  68242. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  68243. var _this = this;
  68244. this._renderingCanvas = _renderingCanvas;
  68245. this._loadingText = _loadingText;
  68246. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  68247. // Resize
  68248. this._resizeLoadingUI = function () {
  68249. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  68250. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  68251. if (!_this._loadingDiv) {
  68252. return;
  68253. }
  68254. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  68255. _this._loadingDiv.style.left = canvasRect.left + "px";
  68256. _this._loadingDiv.style.top = canvasRect.top + "px";
  68257. _this._loadingDiv.style.width = canvasRect.width + "px";
  68258. _this._loadingDiv.style.height = canvasRect.height + "px";
  68259. };
  68260. }
  68261. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  68262. if (this._loadingDiv) {
  68263. // Do not add a loading screen if there is already one
  68264. return;
  68265. }
  68266. this._loadingDiv = document.createElement("div");
  68267. this._loadingDiv.id = "babylonjsLoadingDiv";
  68268. this._loadingDiv.style.opacity = "0";
  68269. this._loadingDiv.style.transition = "opacity 1.5s ease";
  68270. this._loadingDiv.style.pointerEvents = "none";
  68271. // Loading text
  68272. this._loadingTextDiv = document.createElement("div");
  68273. this._loadingTextDiv.style.position = "absolute";
  68274. this._loadingTextDiv.style.left = "0";
  68275. this._loadingTextDiv.style.top = "50%";
  68276. this._loadingTextDiv.style.marginTop = "80px";
  68277. this._loadingTextDiv.style.width = "100%";
  68278. this._loadingTextDiv.style.height = "20px";
  68279. this._loadingTextDiv.style.fontFamily = "Arial";
  68280. this._loadingTextDiv.style.fontSize = "14px";
  68281. this._loadingTextDiv.style.color = "white";
  68282. this._loadingTextDiv.style.textAlign = "center";
  68283. this._loadingTextDiv.innerHTML = "Loading";
  68284. this._loadingDiv.appendChild(this._loadingTextDiv);
  68285. //set the predefined text
  68286. this._loadingTextDiv.innerHTML = this._loadingText;
  68287. // Generating keyframes
  68288. var style = document.createElement('style');
  68289. style.type = 'text/css';
  68290. 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 }";
  68291. style.innerHTML = keyFrames;
  68292. document.getElementsByTagName('head')[0].appendChild(style);
  68293. // Loading img
  68294. var imgBack = new Image();
  68295. 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";
  68296. imgBack.style.position = "absolute";
  68297. imgBack.style.left = "50%";
  68298. imgBack.style.top = "50%";
  68299. imgBack.style.marginLeft = "-60px";
  68300. imgBack.style.marginTop = "-60px";
  68301. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  68302. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  68303. imgBack.style.transformOrigin = "50% 50%";
  68304. imgBack.style.webkitTransformOrigin = "50% 50%";
  68305. this._loadingDiv.appendChild(imgBack);
  68306. this._resizeLoadingUI();
  68307. window.addEventListener("resize", this._resizeLoadingUI);
  68308. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68309. document.body.appendChild(this._loadingDiv);
  68310. this._loadingDiv.style.opacity = "1";
  68311. };
  68312. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  68313. var _this = this;
  68314. if (!this._loadingDiv) {
  68315. return;
  68316. }
  68317. var onTransitionEnd = function () {
  68318. if (!_this._loadingDiv) {
  68319. return;
  68320. }
  68321. document.body.removeChild(_this._loadingDiv);
  68322. window.removeEventListener("resize", _this._resizeLoadingUI);
  68323. _this._loadingDiv = null;
  68324. };
  68325. this._loadingDiv.style.opacity = "0";
  68326. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  68327. };
  68328. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  68329. set: function (text) {
  68330. this._loadingText = text;
  68331. if (this._loadingTextDiv) {
  68332. this._loadingTextDiv.innerHTML = this._loadingText;
  68333. }
  68334. },
  68335. enumerable: true,
  68336. configurable: true
  68337. });
  68338. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  68339. get: function () {
  68340. return this._loadingDivBackgroundColor;
  68341. },
  68342. set: function (color) {
  68343. this._loadingDivBackgroundColor = color;
  68344. if (!this._loadingDiv) {
  68345. return;
  68346. }
  68347. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68348. },
  68349. enumerable: true,
  68350. configurable: true
  68351. });
  68352. return DefaultLoadingScreen;
  68353. }());
  68354. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  68355. })(BABYLON || (BABYLON = {}));
  68356. //# sourceMappingURL=babylon.loadingScreen.js.map
  68357. var BABYLON;
  68358. (function (BABYLON) {
  68359. var SceneLoaderProgressEvent = /** @class */ (function () {
  68360. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  68361. this.lengthComputable = lengthComputable;
  68362. this.loaded = loaded;
  68363. this.total = total;
  68364. }
  68365. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  68366. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  68367. };
  68368. return SceneLoaderProgressEvent;
  68369. }());
  68370. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  68371. var SceneLoader = /** @class */ (function () {
  68372. function SceneLoader() {
  68373. }
  68374. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  68375. get: function () {
  68376. return 0;
  68377. },
  68378. enumerable: true,
  68379. configurable: true
  68380. });
  68381. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  68382. get: function () {
  68383. return 1;
  68384. },
  68385. enumerable: true,
  68386. configurable: true
  68387. });
  68388. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  68389. get: function () {
  68390. return 2;
  68391. },
  68392. enumerable: true,
  68393. configurable: true
  68394. });
  68395. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  68396. get: function () {
  68397. return 3;
  68398. },
  68399. enumerable: true,
  68400. configurable: true
  68401. });
  68402. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  68403. get: function () {
  68404. return SceneLoader._ForceFullSceneLoadingForIncremental;
  68405. },
  68406. set: function (value) {
  68407. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  68408. },
  68409. enumerable: true,
  68410. configurable: true
  68411. });
  68412. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  68413. get: function () {
  68414. return SceneLoader._ShowLoadingScreen;
  68415. },
  68416. set: function (value) {
  68417. SceneLoader._ShowLoadingScreen = value;
  68418. },
  68419. enumerable: true,
  68420. configurable: true
  68421. });
  68422. Object.defineProperty(SceneLoader, "loggingLevel", {
  68423. get: function () {
  68424. return SceneLoader._loggingLevel;
  68425. },
  68426. set: function (value) {
  68427. SceneLoader._loggingLevel = value;
  68428. },
  68429. enumerable: true,
  68430. configurable: true
  68431. });
  68432. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  68433. get: function () {
  68434. return SceneLoader._CleanBoneMatrixWeights;
  68435. },
  68436. set: function (value) {
  68437. SceneLoader._CleanBoneMatrixWeights = value;
  68438. },
  68439. enumerable: true,
  68440. configurable: true
  68441. });
  68442. SceneLoader._getDefaultPlugin = function () {
  68443. return SceneLoader._registeredPlugins[".babylon"];
  68444. };
  68445. SceneLoader._getPluginForExtension = function (extension) {
  68446. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  68447. if (registeredPlugin) {
  68448. return registeredPlugin;
  68449. }
  68450. 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");
  68451. return SceneLoader._getDefaultPlugin();
  68452. };
  68453. SceneLoader._getPluginForDirectLoad = function (data) {
  68454. for (var extension in SceneLoader._registeredPlugins) {
  68455. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  68456. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  68457. return SceneLoader._registeredPlugins[extension];
  68458. }
  68459. }
  68460. return SceneLoader._getDefaultPlugin();
  68461. };
  68462. SceneLoader._getPluginForFilename = function (sceneFilename) {
  68463. if (sceneFilename.name) {
  68464. sceneFilename = sceneFilename.name;
  68465. }
  68466. var queryStringPosition = sceneFilename.indexOf("?");
  68467. if (queryStringPosition !== -1) {
  68468. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  68469. }
  68470. var dotPosition = sceneFilename.lastIndexOf(".");
  68471. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  68472. return SceneLoader._getPluginForExtension(extension);
  68473. };
  68474. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  68475. SceneLoader._getDirectLoad = function (sceneFilename) {
  68476. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  68477. return sceneFilename.substr(5);
  68478. }
  68479. return null;
  68480. };
  68481. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  68482. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  68483. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  68484. var plugin;
  68485. if (registeredPlugin.plugin.createPlugin) {
  68486. plugin = registeredPlugin.plugin.createPlugin();
  68487. }
  68488. else {
  68489. plugin = registeredPlugin.plugin;
  68490. }
  68491. var useArrayBuffer = registeredPlugin.isBinary;
  68492. var database;
  68493. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  68494. var dataCallback = function (data, responseURL) {
  68495. if (scene.isDisposed) {
  68496. onError("Scene has been disposed");
  68497. return;
  68498. }
  68499. scene.database = database;
  68500. onSuccess(plugin, data, responseURL);
  68501. };
  68502. var request = null;
  68503. var pluginDisposed = false;
  68504. var onDisposeObservable = plugin.onDisposeObservable;
  68505. if (onDisposeObservable) {
  68506. onDisposeObservable.add(function () {
  68507. pluginDisposed = true;
  68508. if (request) {
  68509. request.abort();
  68510. request = null;
  68511. }
  68512. onDispose();
  68513. });
  68514. }
  68515. var manifestChecked = function () {
  68516. if (pluginDisposed) {
  68517. return;
  68518. }
  68519. var url = rootUrl + sceneFilename;
  68520. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  68521. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  68522. } : undefined, database, useArrayBuffer, function (request, exception) {
  68523. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  68524. });
  68525. };
  68526. if (directLoad) {
  68527. dataCallback(directLoad);
  68528. return plugin;
  68529. }
  68530. if (rootUrl.indexOf("file:") === -1) {
  68531. var engine = scene.getEngine();
  68532. var canUseOfflineSupport = engine.enableOfflineSupport;
  68533. if (canUseOfflineSupport) {
  68534. // Also check for exceptions
  68535. var exceptionFound = false;
  68536. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  68537. var regex = _a[_i];
  68538. if (regex.test(rootUrl + sceneFilename)) {
  68539. exceptionFound = true;
  68540. break;
  68541. }
  68542. }
  68543. canUseOfflineSupport = !exceptionFound;
  68544. }
  68545. if (canUseOfflineSupport) {
  68546. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  68547. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  68548. }
  68549. else {
  68550. manifestChecked();
  68551. }
  68552. }
  68553. // Loading file from disk via input file or drag'n'drop
  68554. else {
  68555. var fileOrString = sceneFilename;
  68556. if (fileOrString.name) { // File
  68557. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  68558. }
  68559. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  68560. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  68561. }
  68562. else {
  68563. onError("Unable to find file named " + sceneFilename);
  68564. }
  68565. }
  68566. return plugin;
  68567. };
  68568. // Public functions
  68569. SceneLoader.GetPluginForExtension = function (extension) {
  68570. return SceneLoader._getPluginForExtension(extension).plugin;
  68571. };
  68572. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  68573. return !!SceneLoader._registeredPlugins[extension];
  68574. };
  68575. SceneLoader.RegisterPlugin = function (plugin) {
  68576. if (typeof plugin.extensions === "string") {
  68577. var extension = plugin.extensions;
  68578. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68579. plugin: plugin,
  68580. isBinary: false
  68581. };
  68582. }
  68583. else {
  68584. var extensions = plugin.extensions;
  68585. Object.keys(extensions).forEach(function (extension) {
  68586. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68587. plugin: plugin,
  68588. isBinary: extensions[extension].isBinary
  68589. };
  68590. });
  68591. }
  68592. };
  68593. /**
  68594. * Import meshes into a scene
  68595. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68596. * @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)
  68597. * @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)
  68598. * @param scene the instance of BABYLON.Scene to append to
  68599. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  68600. * @param onProgress a callback with a progress event for each file being loaded
  68601. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68602. * @param pluginExtension the extension used to determine the plugin
  68603. * @returns The loaded plugin
  68604. */
  68605. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68606. if (sceneFilename === void 0) { sceneFilename = ""; }
  68607. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68608. if (onSuccess === void 0) { onSuccess = null; }
  68609. if (onProgress === void 0) { onProgress = null; }
  68610. if (onError === void 0) { onError = null; }
  68611. if (pluginExtension === void 0) { pluginExtension = null; }
  68612. if (!scene) {
  68613. BABYLON.Tools.Error("No scene available to import mesh to");
  68614. return null;
  68615. }
  68616. if (!sceneFilename) {
  68617. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68618. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68619. }
  68620. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68621. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68622. return null;
  68623. }
  68624. var loadingToken = {};
  68625. scene._addPendingData(loadingToken);
  68626. var disposeHandler = function () {
  68627. scene._removePendingData(loadingToken);
  68628. };
  68629. var errorHandler = function (message, exception) {
  68630. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  68631. if (onError) {
  68632. onError(scene, errorMessage, exception);
  68633. }
  68634. else {
  68635. BABYLON.Tools.Error(errorMessage);
  68636. // should the exception be thrown?
  68637. }
  68638. disposeHandler();
  68639. };
  68640. var progressHandler = onProgress ? function (event) {
  68641. try {
  68642. onProgress(event);
  68643. }
  68644. catch (e) {
  68645. errorHandler("Error in onProgress callback", e);
  68646. }
  68647. } : undefined;
  68648. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  68649. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  68650. if (onSuccess) {
  68651. try {
  68652. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  68653. }
  68654. catch (e) {
  68655. errorHandler("Error in onSuccess callback", e);
  68656. }
  68657. }
  68658. scene._removePendingData(loadingToken);
  68659. };
  68660. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68661. if (plugin.rewriteRootURL) {
  68662. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  68663. }
  68664. if (sceneFilename === "") {
  68665. if (sceneFilename === "") {
  68666. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68667. }
  68668. }
  68669. if (plugin.importMesh) {
  68670. var syncedPlugin = plugin;
  68671. var meshes = new Array();
  68672. var particleSystems = new Array();
  68673. var skeletons = new Array();
  68674. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  68675. return;
  68676. }
  68677. scene.loadingPluginName = plugin.name;
  68678. successHandler(meshes, particleSystems, skeletons, []);
  68679. }
  68680. else {
  68681. var asyncedPlugin = plugin;
  68682. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  68683. scene.loadingPluginName = plugin.name;
  68684. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  68685. }).catch(function (error) {
  68686. errorHandler(error.message, error);
  68687. });
  68688. }
  68689. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68690. };
  68691. /**
  68692. * Import meshes into a scene
  68693. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68694. * @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)
  68695. * @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)
  68696. * @param scene the instance of BABYLON.Scene to append to
  68697. * @param onProgress a callback with a progress event for each file being loaded
  68698. * @param pluginExtension the extension used to determine the plugin
  68699. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  68700. */
  68701. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68702. if (sceneFilename === void 0) { sceneFilename = ""; }
  68703. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68704. if (onProgress === void 0) { onProgress = null; }
  68705. if (pluginExtension === void 0) { pluginExtension = null; }
  68706. return new Promise(function (resolve, reject) {
  68707. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  68708. resolve({
  68709. meshes: meshes,
  68710. particleSystems: particleSystems,
  68711. skeletons: skeletons,
  68712. animationGroups: animationGroups
  68713. });
  68714. }, onProgress, function (scene, message, exception) {
  68715. reject(exception || new Error(message));
  68716. }, pluginExtension);
  68717. });
  68718. };
  68719. /**
  68720. * Load a scene
  68721. * @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)
  68722. * @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)
  68723. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68724. * @param onSuccess a callback with the scene when import succeeds
  68725. * @param onProgress a callback with a progress event for each file being loaded
  68726. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68727. * @param pluginExtension the extension used to determine the plugin
  68728. * @returns The loaded plugin
  68729. */
  68730. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  68731. if (onSuccess === void 0) { onSuccess = null; }
  68732. if (onProgress === void 0) { onProgress = null; }
  68733. if (onError === void 0) { onError = null; }
  68734. if (pluginExtension === void 0) { pluginExtension = null; }
  68735. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  68736. };
  68737. /**
  68738. * Load a scene
  68739. * @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)
  68740. * @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)
  68741. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68742. * @param onProgress a callback with a progress event for each file being loaded
  68743. * @param pluginExtension the extension used to determine the plugin
  68744. * @returns The loaded scene
  68745. */
  68746. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  68747. if (onProgress === void 0) { onProgress = null; }
  68748. if (pluginExtension === void 0) { pluginExtension = null; }
  68749. return new Promise(function (resolve, reject) {
  68750. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  68751. resolve(scene);
  68752. }, onProgress, function (scene, message, exception) {
  68753. reject(exception || new Error(message));
  68754. }, pluginExtension);
  68755. });
  68756. };
  68757. /**
  68758. * Append a scene
  68759. * @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)
  68760. * @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)
  68761. * @param scene is the instance of BABYLON.Scene to append to
  68762. * @param onSuccess a callback with the scene when import succeeds
  68763. * @param onProgress a callback with a progress event for each file being loaded
  68764. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68765. * @param pluginExtension the extension used to determine the plugin
  68766. * @returns The loaded plugin
  68767. */
  68768. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68769. if (sceneFilename === void 0) { sceneFilename = ""; }
  68770. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68771. if (onSuccess === void 0) { onSuccess = null; }
  68772. if (onProgress === void 0) { onProgress = null; }
  68773. if (onError === void 0) { onError = null; }
  68774. if (pluginExtension === void 0) { pluginExtension = null; }
  68775. if (!scene) {
  68776. BABYLON.Tools.Error("No scene available to append to");
  68777. return null;
  68778. }
  68779. if (!sceneFilename) {
  68780. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68781. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68782. }
  68783. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68784. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68785. return null;
  68786. }
  68787. if (SceneLoader.ShowLoadingScreen) {
  68788. scene.getEngine().displayLoadingUI();
  68789. }
  68790. var loadingToken = {};
  68791. scene._addPendingData(loadingToken);
  68792. var disposeHandler = function () {
  68793. scene._removePendingData(loadingToken);
  68794. scene.getEngine().hideLoadingUI();
  68795. };
  68796. var errorHandler = function (message, exception) {
  68797. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68798. if (onError) {
  68799. onError(scene, errorMessage, exception);
  68800. }
  68801. else {
  68802. BABYLON.Tools.Error(errorMessage);
  68803. // should the exception be thrown?
  68804. }
  68805. disposeHandler();
  68806. };
  68807. var progressHandler = onProgress ? function (event) {
  68808. try {
  68809. onProgress(event);
  68810. }
  68811. catch (e) {
  68812. errorHandler("Error in onProgress callback", e);
  68813. }
  68814. } : undefined;
  68815. var successHandler = function () {
  68816. if (onSuccess) {
  68817. try {
  68818. onSuccess(scene);
  68819. }
  68820. catch (e) {
  68821. errorHandler("Error in onSuccess callback", e);
  68822. }
  68823. }
  68824. scene._removePendingData(loadingToken);
  68825. };
  68826. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68827. if (sceneFilename === "") {
  68828. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68829. }
  68830. if (plugin.load) {
  68831. var syncedPlugin = plugin;
  68832. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68833. return;
  68834. }
  68835. scene.loadingPluginName = plugin.name;
  68836. successHandler();
  68837. }
  68838. else {
  68839. var asyncedPlugin = plugin;
  68840. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68841. scene.loadingPluginName = plugin.name;
  68842. successHandler();
  68843. }).catch(function (error) {
  68844. errorHandler(error.message, error);
  68845. });
  68846. }
  68847. if (SceneLoader.ShowLoadingScreen) {
  68848. scene.executeWhenReady(function () {
  68849. scene.getEngine().hideLoadingUI();
  68850. });
  68851. }
  68852. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68853. };
  68854. /**
  68855. * Append a scene
  68856. * @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)
  68857. * @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)
  68858. * @param scene is the instance of BABYLON.Scene to append to
  68859. * @param onProgress a callback with a progress event for each file being loaded
  68860. * @param pluginExtension the extension used to determine the plugin
  68861. * @returns The given scene
  68862. */
  68863. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68864. if (sceneFilename === void 0) { sceneFilename = ""; }
  68865. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68866. if (onProgress === void 0) { onProgress = null; }
  68867. if (pluginExtension === void 0) { pluginExtension = null; }
  68868. return new Promise(function (resolve, reject) {
  68869. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68870. resolve(scene);
  68871. }, onProgress, function (scene, message, exception) {
  68872. reject(exception || new Error(message));
  68873. }, pluginExtension);
  68874. });
  68875. };
  68876. /**
  68877. * Load a scene into an asset container
  68878. * @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)
  68879. * @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)
  68880. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68881. * @param onSuccess a callback with the scene when import succeeds
  68882. * @param onProgress a callback with a progress event for each file being loaded
  68883. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68884. * @param pluginExtension the extension used to determine the plugin
  68885. * @returns The loaded plugin
  68886. */
  68887. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68888. if (sceneFilename === void 0) { sceneFilename = ""; }
  68889. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68890. if (onSuccess === void 0) { onSuccess = null; }
  68891. if (onProgress === void 0) { onProgress = null; }
  68892. if (onError === void 0) { onError = null; }
  68893. if (pluginExtension === void 0) { pluginExtension = null; }
  68894. if (!scene) {
  68895. BABYLON.Tools.Error("No scene available to load asset container to");
  68896. return null;
  68897. }
  68898. if (!sceneFilename) {
  68899. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68900. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68901. }
  68902. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68903. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68904. return null;
  68905. }
  68906. var loadingToken = {};
  68907. scene._addPendingData(loadingToken);
  68908. var disposeHandler = function () {
  68909. scene._removePendingData(loadingToken);
  68910. };
  68911. var errorHandler = function (message, exception) {
  68912. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68913. if (onError) {
  68914. onError(scene, errorMessage, exception);
  68915. }
  68916. else {
  68917. BABYLON.Tools.Error(errorMessage);
  68918. // should the exception be thrown?
  68919. }
  68920. disposeHandler();
  68921. };
  68922. var progressHandler = onProgress ? function (event) {
  68923. try {
  68924. onProgress(event);
  68925. }
  68926. catch (e) {
  68927. errorHandler("Error in onProgress callback", e);
  68928. }
  68929. } : undefined;
  68930. var successHandler = function (assets) {
  68931. if (onSuccess) {
  68932. try {
  68933. onSuccess(assets);
  68934. }
  68935. catch (e) {
  68936. errorHandler("Error in onSuccess callback", e);
  68937. }
  68938. }
  68939. scene._removePendingData(loadingToken);
  68940. };
  68941. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68942. if (plugin.loadAssetContainer) {
  68943. var syncedPlugin = plugin;
  68944. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68945. if (!assetContainer) {
  68946. return;
  68947. }
  68948. scene.loadingPluginName = plugin.name;
  68949. successHandler(assetContainer);
  68950. }
  68951. else if (plugin.loadAssetContainerAsync) {
  68952. var asyncedPlugin = plugin;
  68953. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68954. scene.loadingPluginName = plugin.name;
  68955. successHandler(assetContainer);
  68956. }).catch(function (error) {
  68957. errorHandler(error.message, error);
  68958. });
  68959. }
  68960. else {
  68961. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68962. }
  68963. if (SceneLoader.ShowLoadingScreen) {
  68964. scene.executeWhenReady(function () {
  68965. scene.getEngine().hideLoadingUI();
  68966. });
  68967. }
  68968. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68969. };
  68970. /**
  68971. * Load a scene into an asset container
  68972. * @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)
  68973. * @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)
  68974. * @param scene is the instance of BABYLON.Scene to append to
  68975. * @param onProgress a callback with a progress event for each file being loaded
  68976. * @param pluginExtension the extension used to determine the plugin
  68977. * @returns The loaded asset container
  68978. */
  68979. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68980. if (sceneFilename === void 0) { sceneFilename = ""; }
  68981. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68982. if (onProgress === void 0) { onProgress = null; }
  68983. if (pluginExtension === void 0) { pluginExtension = null; }
  68984. return new Promise(function (resolve, reject) {
  68985. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68986. resolve(assetContainer);
  68987. }, onProgress, function (scene, message, exception) {
  68988. reject(exception || new Error(message));
  68989. }, pluginExtension);
  68990. });
  68991. };
  68992. // Flags
  68993. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68994. SceneLoader._ShowLoadingScreen = true;
  68995. SceneLoader._CleanBoneMatrixWeights = false;
  68996. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68997. // Members
  68998. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68999. SceneLoader._registeredPlugins = {};
  69000. return SceneLoader;
  69001. }());
  69002. BABYLON.SceneLoader = SceneLoader;
  69003. ;
  69004. })(BABYLON || (BABYLON = {}));
  69005. //# sourceMappingURL=babylon.sceneLoader.js.map
  69006. var BABYLON;
  69007. (function (BABYLON) {
  69008. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69009. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69010. var parsedMaterial = parsedData.materials[index];
  69011. if (parsedMaterial.id === id) {
  69012. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69013. }
  69014. }
  69015. return null;
  69016. };
  69017. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69018. for (var i in names) {
  69019. if (mesh.name === names[i]) {
  69020. hierarchyIds.push(mesh.id);
  69021. return true;
  69022. }
  69023. }
  69024. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69025. hierarchyIds.push(mesh.id);
  69026. return true;
  69027. }
  69028. return false;
  69029. };
  69030. var logOperation = function (operation, producer) {
  69031. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69032. };
  69033. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69034. if (addToScene === void 0) { addToScene = false; }
  69035. var container = new BABYLON.AssetContainer(scene);
  69036. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69037. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69038. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69039. // and avoid problems with multiple concurrent .babylon loads.
  69040. var log = "importScene has failed JSON parse";
  69041. try {
  69042. var parsedData = JSON.parse(data);
  69043. log = "";
  69044. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69045. var index;
  69046. var cache;
  69047. // Lights
  69048. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69049. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69050. var parsedLight = parsedData.lights[index];
  69051. var light = BABYLON.Light.Parse(parsedLight, scene);
  69052. if (light) {
  69053. container.lights.push(light);
  69054. log += (index === 0 ? "\n\tLights:" : "");
  69055. log += "\n\t\t" + light.toString(fullDetails);
  69056. }
  69057. }
  69058. }
  69059. // Animations
  69060. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69061. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69062. var parsedAnimation = parsedData.animations[index];
  69063. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69064. scene.animations.push(animation);
  69065. container.animations.push(animation);
  69066. log += (index === 0 ? "\n\tAnimations:" : "");
  69067. log += "\n\t\t" + animation.toString(fullDetails);
  69068. }
  69069. }
  69070. // Materials
  69071. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69072. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69073. var parsedMaterial = parsedData.materials[index];
  69074. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69075. container.materials.push(mat);
  69076. log += (index === 0 ? "\n\tMaterials:" : "");
  69077. log += "\n\t\t" + mat.toString(fullDetails);
  69078. }
  69079. }
  69080. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69081. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69082. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69083. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69084. container.multiMaterials.push(mmat);
  69085. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69086. log += "\n\t\t" + mmat.toString(fullDetails);
  69087. }
  69088. }
  69089. // Morph targets
  69090. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69091. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69092. var managerData = _a[_i];
  69093. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69094. }
  69095. }
  69096. // Skeletons
  69097. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69098. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  69099. var parsedSkeleton = parsedData.skeletons[index];
  69100. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69101. container.skeletons.push(skeleton);
  69102. log += (index === 0 ? "\n\tSkeletons:" : "");
  69103. log += "\n\t\t" + skeleton.toString(fullDetails);
  69104. }
  69105. }
  69106. // Geometries
  69107. var geometries = parsedData.geometries;
  69108. if (geometries !== undefined && geometries !== null) {
  69109. var addedGeometry = new Array();
  69110. // Boxes
  69111. var boxes = geometries.boxes;
  69112. if (boxes !== undefined && boxes !== null) {
  69113. for (index = 0, cache = boxes.length; index < cache; index++) {
  69114. var parsedBox = boxes[index];
  69115. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  69116. }
  69117. }
  69118. // Spheres
  69119. var spheres = geometries.spheres;
  69120. if (spheres !== undefined && spheres !== null) {
  69121. for (index = 0, cache = spheres.length; index < cache; index++) {
  69122. var parsedSphere = spheres[index];
  69123. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  69124. }
  69125. }
  69126. // Cylinders
  69127. var cylinders = geometries.cylinders;
  69128. if (cylinders !== undefined && cylinders !== null) {
  69129. for (index = 0, cache = cylinders.length; index < cache; index++) {
  69130. var parsedCylinder = cylinders[index];
  69131. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  69132. }
  69133. }
  69134. // Toruses
  69135. var toruses = geometries.toruses;
  69136. if (toruses !== undefined && toruses !== null) {
  69137. for (index = 0, cache = toruses.length; index < cache; index++) {
  69138. var parsedTorus = toruses[index];
  69139. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  69140. }
  69141. }
  69142. // Grounds
  69143. var grounds = geometries.grounds;
  69144. if (grounds !== undefined && grounds !== null) {
  69145. for (index = 0, cache = grounds.length; index < cache; index++) {
  69146. var parsedGround = grounds[index];
  69147. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  69148. }
  69149. }
  69150. // Planes
  69151. var planes = geometries.planes;
  69152. if (planes !== undefined && planes !== null) {
  69153. for (index = 0, cache = planes.length; index < cache; index++) {
  69154. var parsedPlane = planes[index];
  69155. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  69156. }
  69157. }
  69158. // TorusKnots
  69159. var torusKnots = geometries.torusKnots;
  69160. if (torusKnots !== undefined && torusKnots !== null) {
  69161. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  69162. var parsedTorusKnot = torusKnots[index];
  69163. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  69164. }
  69165. }
  69166. // VertexData
  69167. var vertexData = geometries.vertexData;
  69168. if (vertexData !== undefined && vertexData !== null) {
  69169. for (index = 0, cache = vertexData.length; index < cache; index++) {
  69170. var parsedVertexData = vertexData[index];
  69171. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  69172. }
  69173. }
  69174. addedGeometry.forEach(function (g) {
  69175. if (g) {
  69176. container.geometries.push(g);
  69177. }
  69178. });
  69179. }
  69180. // Transform nodes
  69181. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  69182. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  69183. var parsedTransformNode = parsedData.transformNodes[index];
  69184. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  69185. container.transformNodes.push(node);
  69186. }
  69187. }
  69188. // Meshes
  69189. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69190. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69191. var parsedMesh = parsedData.meshes[index];
  69192. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69193. container.meshes.push(mesh);
  69194. log += (index === 0 ? "\n\tMeshes:" : "");
  69195. log += "\n\t\t" + mesh.toString(fullDetails);
  69196. }
  69197. }
  69198. // Cameras
  69199. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  69200. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  69201. var parsedCamera = parsedData.cameras[index];
  69202. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  69203. container.cameras.push(camera);
  69204. log += (index === 0 ? "\n\tCameras:" : "");
  69205. log += "\n\t\t" + camera.toString(fullDetails);
  69206. }
  69207. }
  69208. // Browsing all the graph to connect the dots
  69209. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  69210. var camera = scene.cameras[index];
  69211. if (camera._waitingParentId) {
  69212. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  69213. camera._waitingParentId = null;
  69214. }
  69215. }
  69216. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69217. var light_1 = scene.lights[index];
  69218. if (light_1 && light_1._waitingParentId) {
  69219. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  69220. light_1._waitingParentId = null;
  69221. }
  69222. }
  69223. // Sounds
  69224. // TODO: add sound
  69225. var loadedSounds = [];
  69226. var loadedSound;
  69227. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69228. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69229. var parsedSound = parsedData.sounds[index];
  69230. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69231. if (!parsedSound.url)
  69232. parsedSound.url = parsedSound.name;
  69233. if (!loadedSounds[parsedSound.url]) {
  69234. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69235. loadedSounds[parsedSound.url] = loadedSound;
  69236. container.sounds.push(loadedSound);
  69237. }
  69238. else {
  69239. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69240. }
  69241. }
  69242. else {
  69243. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69244. }
  69245. }
  69246. }
  69247. loadedSounds = [];
  69248. // Connect parents & children and parse actions
  69249. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  69250. var transformNode = scene.transformNodes[index];
  69251. if (transformNode._waitingParentId) {
  69252. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  69253. transformNode._waitingParentId = null;
  69254. }
  69255. }
  69256. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69257. var mesh = scene.meshes[index];
  69258. if (mesh._waitingParentId) {
  69259. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  69260. mesh._waitingParentId = null;
  69261. }
  69262. if (mesh._waitingActions) {
  69263. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  69264. mesh._waitingActions = null;
  69265. }
  69266. }
  69267. // freeze world matrix application
  69268. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69269. var currentMesh = scene.meshes[index];
  69270. if (currentMesh._waitingFreezeWorldMatrix) {
  69271. currentMesh.freezeWorldMatrix();
  69272. currentMesh._waitingFreezeWorldMatrix = null;
  69273. }
  69274. else {
  69275. currentMesh.computeWorldMatrix(true);
  69276. }
  69277. }
  69278. // Shadows
  69279. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  69280. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  69281. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  69282. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  69283. // SG would be available on their associated lights
  69284. }
  69285. }
  69286. // Lights exclusions / inclusions
  69287. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69288. var light_2 = scene.lights[index];
  69289. // Excluded check
  69290. if (light_2._excludedMeshesIds.length > 0) {
  69291. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  69292. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  69293. if (excludedMesh) {
  69294. light_2.excludedMeshes.push(excludedMesh);
  69295. }
  69296. }
  69297. light_2._excludedMeshesIds = [];
  69298. }
  69299. // Included check
  69300. if (light_2._includedOnlyMeshesIds.length > 0) {
  69301. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  69302. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  69303. if (includedOnlyMesh) {
  69304. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  69305. }
  69306. }
  69307. light_2._includedOnlyMeshesIds = [];
  69308. }
  69309. }
  69310. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  69311. // Actions (scene)
  69312. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  69313. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  69314. }
  69315. if (!addToScene) {
  69316. container.removeAllFromScene();
  69317. }
  69318. }
  69319. catch (err) {
  69320. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  69321. if (onError) {
  69322. onError(msg, err);
  69323. }
  69324. else {
  69325. BABYLON.Tools.Log(msg);
  69326. throw err;
  69327. }
  69328. }
  69329. finally {
  69330. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69331. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69332. }
  69333. }
  69334. return container;
  69335. };
  69336. BABYLON.SceneLoader.RegisterPlugin({
  69337. name: "babylon.js",
  69338. extensions: ".babylon",
  69339. canDirectLoad: function (data) {
  69340. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  69341. return true;
  69342. }
  69343. return false;
  69344. },
  69345. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  69346. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69347. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69348. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69349. // and avoid problems with multiple concurrent .babylon loads.
  69350. var log = "importMesh has failed JSON parse";
  69351. try {
  69352. var parsedData = JSON.parse(data);
  69353. log = "";
  69354. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69355. if (!meshesNames) {
  69356. meshesNames = null;
  69357. }
  69358. else if (!Array.isArray(meshesNames)) {
  69359. meshesNames = [meshesNames];
  69360. }
  69361. var hierarchyIds = new Array();
  69362. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69363. var loadedSkeletonsIds = [];
  69364. var loadedMaterialsIds = [];
  69365. var index;
  69366. var cache;
  69367. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69368. var parsedMesh = parsedData.meshes[index];
  69369. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  69370. if (meshesNames !== null) {
  69371. // Remove found mesh name from list.
  69372. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  69373. }
  69374. //Geometry?
  69375. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  69376. //does the file contain geometries?
  69377. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  69378. //find the correct geometry and add it to the scene
  69379. var found = false;
  69380. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  69381. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  69382. return;
  69383. }
  69384. else {
  69385. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  69386. if (parsedGeometryData.id === parsedMesh.geometryId) {
  69387. switch (geometryType) {
  69388. case "boxes":
  69389. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  69390. break;
  69391. case "spheres":
  69392. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  69393. break;
  69394. case "cylinders":
  69395. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  69396. break;
  69397. case "toruses":
  69398. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  69399. break;
  69400. case "grounds":
  69401. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  69402. break;
  69403. case "planes":
  69404. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  69405. break;
  69406. case "torusKnots":
  69407. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  69408. break;
  69409. case "vertexData":
  69410. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  69411. break;
  69412. }
  69413. found = true;
  69414. }
  69415. });
  69416. }
  69417. });
  69418. if (found === false) {
  69419. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  69420. }
  69421. }
  69422. }
  69423. // Material ?
  69424. if (parsedMesh.materialId) {
  69425. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  69426. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69427. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  69428. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  69429. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  69430. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  69431. var subMatId = parsedMultiMaterial.materials[matIndex];
  69432. loadedMaterialsIds.push(subMatId);
  69433. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  69434. if (mat) {
  69435. log += "\n\tMaterial " + mat.toString(fullDetails);
  69436. }
  69437. }
  69438. loadedMaterialsIds.push(parsedMultiMaterial.id);
  69439. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69440. if (mmat) {
  69441. materialFound = true;
  69442. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  69443. }
  69444. break;
  69445. }
  69446. }
  69447. }
  69448. if (materialFound === false) {
  69449. loadedMaterialsIds.push(parsedMesh.materialId);
  69450. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  69451. if (!mat) {
  69452. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  69453. }
  69454. else {
  69455. log += "\n\tMaterial " + mat.toString(fullDetails);
  69456. }
  69457. }
  69458. }
  69459. // Skeleton ?
  69460. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69461. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  69462. if (skeletonAlreadyLoaded === false) {
  69463. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  69464. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  69465. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  69466. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69467. skeletons.push(skeleton);
  69468. loadedSkeletonsIds.push(parsedSkeleton.id);
  69469. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  69470. }
  69471. }
  69472. }
  69473. }
  69474. // Morph targets ?
  69475. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69476. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69477. var managerData = _a[_i];
  69478. BABYLON.MorphTargetManager.Parse(managerData, scene);
  69479. }
  69480. }
  69481. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69482. meshes.push(mesh);
  69483. log += "\n\tMesh " + mesh.toString(fullDetails);
  69484. }
  69485. }
  69486. // Connecting parents
  69487. var currentMesh;
  69488. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69489. currentMesh = scene.meshes[index];
  69490. if (currentMesh._waitingParentId) {
  69491. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  69492. currentMesh._waitingParentId = null;
  69493. }
  69494. }
  69495. // freeze and compute world matrix application
  69496. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69497. currentMesh = scene.meshes[index];
  69498. if (currentMesh._waitingFreezeWorldMatrix) {
  69499. currentMesh.freezeWorldMatrix();
  69500. currentMesh._waitingFreezeWorldMatrix = null;
  69501. }
  69502. else {
  69503. currentMesh.computeWorldMatrix(true);
  69504. }
  69505. }
  69506. }
  69507. // Particles
  69508. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  69509. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  69510. if (parser) {
  69511. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  69512. var parsedParticleSystem = parsedData.particleSystems[index];
  69513. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  69514. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  69515. }
  69516. }
  69517. }
  69518. }
  69519. return true;
  69520. }
  69521. catch (err) {
  69522. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  69523. if (onError) {
  69524. onError(msg, err);
  69525. }
  69526. else {
  69527. BABYLON.Tools.Log(msg);
  69528. throw err;
  69529. }
  69530. }
  69531. finally {
  69532. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69533. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69534. }
  69535. }
  69536. return false;
  69537. },
  69538. load: function (scene, data, rootUrl, onError) {
  69539. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69540. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69541. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69542. // and avoid problems with multiple concurrent .babylon loads.
  69543. var log = "importScene has failed JSON parse";
  69544. try {
  69545. var parsedData = JSON.parse(data);
  69546. log = "";
  69547. // Scene
  69548. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  69549. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  69550. }
  69551. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  69552. scene.autoClear = parsedData.autoClear;
  69553. }
  69554. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  69555. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  69556. }
  69557. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  69558. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  69559. }
  69560. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  69561. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  69562. }
  69563. // Fog
  69564. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  69565. scene.fogMode = parsedData.fogMode;
  69566. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  69567. scene.fogStart = parsedData.fogStart;
  69568. scene.fogEnd = parsedData.fogEnd;
  69569. scene.fogDensity = parsedData.fogDensity;
  69570. log += "\tFog mode for scene: ";
  69571. switch (scene.fogMode) {
  69572. // getters not compiling, so using hardcoded
  69573. case 1:
  69574. log += "exp\n";
  69575. break;
  69576. case 2:
  69577. log += "exp2\n";
  69578. break;
  69579. case 3:
  69580. log += "linear\n";
  69581. break;
  69582. }
  69583. }
  69584. //Physics
  69585. if (parsedData.physicsEnabled) {
  69586. var physicsPlugin;
  69587. if (parsedData.physicsEngine === "cannon") {
  69588. physicsPlugin = new BABYLON.CannonJSPlugin();
  69589. }
  69590. else if (parsedData.physicsEngine === "oimo") {
  69591. physicsPlugin = new BABYLON.OimoJSPlugin();
  69592. }
  69593. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  69594. //else - default engine, which is currently oimo
  69595. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  69596. scene.enablePhysics(physicsGravity, physicsPlugin);
  69597. }
  69598. // Metadata
  69599. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  69600. scene.metadata = parsedData.metadata;
  69601. }
  69602. //collisions, if defined. otherwise, default is true
  69603. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  69604. scene.collisionsEnabled = parsedData.collisionsEnabled;
  69605. }
  69606. scene.workerCollisions = !!parsedData.workerCollisions;
  69607. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  69608. if (!container) {
  69609. return false;
  69610. }
  69611. if (parsedData.autoAnimate) {
  69612. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  69613. }
  69614. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  69615. scene.setActiveCameraByID(parsedData.activeCameraID);
  69616. }
  69617. // Environment texture
  69618. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  69619. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  69620. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  69621. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  69622. if (parsedData.environmentTextureRotationY) {
  69623. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  69624. }
  69625. scene.environmentTexture = hdrTexture;
  69626. }
  69627. else {
  69628. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  69629. if (parsedData.environmentTextureRotationY) {
  69630. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  69631. }
  69632. scene.environmentTexture = cubeTexture;
  69633. }
  69634. if (parsedData.createDefaultSkybox === true) {
  69635. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  69636. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  69637. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  69638. }
  69639. }
  69640. // Finish
  69641. return true;
  69642. }
  69643. catch (err) {
  69644. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  69645. if (onError) {
  69646. onError(msg, err);
  69647. }
  69648. else {
  69649. BABYLON.Tools.Log(msg);
  69650. throw err;
  69651. }
  69652. }
  69653. finally {
  69654. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69655. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69656. }
  69657. }
  69658. return false;
  69659. },
  69660. loadAssetContainer: function (scene, data, rootUrl, onError) {
  69661. var container = loadAssetContainer(scene, data, rootUrl, onError);
  69662. return container;
  69663. }
  69664. });
  69665. })(BABYLON || (BABYLON = {}));
  69666. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  69667. var BABYLON;
  69668. (function (BABYLON) {
  69669. var FilesInput = /** @class */ (function () {
  69670. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  69671. this.onProcessFileCallback = function () { return true; };
  69672. this._engine = engine;
  69673. this._currentScene = scene;
  69674. this._sceneLoadedCallback = sceneLoadedCallback;
  69675. this._progressCallback = progressCallback;
  69676. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  69677. this._textureLoadingCallback = textureLoadingCallback;
  69678. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  69679. this._onReloadCallback = onReloadCallback;
  69680. this._errorCallback = errorCallback;
  69681. }
  69682. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  69683. var _this = this;
  69684. if (elementToMonitor) {
  69685. this._elementToMonitor = elementToMonitor;
  69686. this._dragEnterHandler = function (e) { _this.drag(e); };
  69687. this._dragOverHandler = function (e) { _this.drag(e); };
  69688. this._dropHandler = function (e) { _this.drop(e); };
  69689. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  69690. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  69691. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  69692. }
  69693. };
  69694. FilesInput.prototype.dispose = function () {
  69695. if (!this._elementToMonitor) {
  69696. return;
  69697. }
  69698. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  69699. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  69700. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  69701. };
  69702. FilesInput.prototype.renderFunction = function () {
  69703. if (this._additionalRenderLoopLogicCallback) {
  69704. this._additionalRenderLoopLogicCallback();
  69705. }
  69706. if (this._currentScene) {
  69707. if (this._textureLoadingCallback) {
  69708. var remaining = this._currentScene.getWaitingItemsCount();
  69709. if (remaining > 0) {
  69710. this._textureLoadingCallback(remaining);
  69711. }
  69712. }
  69713. this._currentScene.render();
  69714. }
  69715. };
  69716. FilesInput.prototype.drag = function (e) {
  69717. e.stopPropagation();
  69718. e.preventDefault();
  69719. };
  69720. FilesInput.prototype.drop = function (eventDrop) {
  69721. eventDrop.stopPropagation();
  69722. eventDrop.preventDefault();
  69723. this.loadFiles(eventDrop);
  69724. };
  69725. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  69726. var _this = this;
  69727. var reader = folder.createReader();
  69728. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  69729. reader.readEntries(function (entries) {
  69730. remaining.count += entries.length;
  69731. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  69732. var entry = entries_1[_i];
  69733. if (entry.isFile) {
  69734. entry.file(function (file) {
  69735. file.correctName = relativePath + file.name;
  69736. files.push(file);
  69737. if (--remaining.count === 0) {
  69738. callback();
  69739. }
  69740. });
  69741. }
  69742. else if (entry.isDirectory) {
  69743. _this._traverseFolder(entry, files, remaining, callback);
  69744. }
  69745. }
  69746. if (--remaining.count) {
  69747. callback();
  69748. }
  69749. });
  69750. };
  69751. FilesInput.prototype._processFiles = function (files) {
  69752. for (var i = 0; i < files.length; i++) {
  69753. var name = files[i].correctName.toLowerCase();
  69754. var extension = name.split('.').pop();
  69755. if (!this.onProcessFileCallback(files[i], name, extension)) {
  69756. continue;
  69757. }
  69758. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  69759. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  69760. this._sceneFileToLoad = files[i];
  69761. }
  69762. else {
  69763. FilesInput.FilesToLoad[name] = files[i];
  69764. }
  69765. }
  69766. };
  69767. FilesInput.prototype.loadFiles = function (event) {
  69768. var _this = this;
  69769. if (this._startingProcessingFilesCallback)
  69770. this._startingProcessingFilesCallback();
  69771. // Handling data transfer via drag'n'drop
  69772. if (event && event.dataTransfer && event.dataTransfer.files) {
  69773. this._filesToLoad = event.dataTransfer.files;
  69774. }
  69775. // Handling files from input files
  69776. if (event && event.target && event.target.files) {
  69777. this._filesToLoad = event.target.files;
  69778. }
  69779. if (this._filesToLoad && this._filesToLoad.length > 0) {
  69780. var files_1 = new Array();
  69781. var folders = [];
  69782. var items = event.dataTransfer ? event.dataTransfer.items : null;
  69783. for (var i = 0; i < this._filesToLoad.length; i++) {
  69784. var fileToLoad = this._filesToLoad[i];
  69785. var name_1 = fileToLoad.name.toLowerCase();
  69786. var entry = void 0;
  69787. fileToLoad.correctName = name_1;
  69788. if (items) {
  69789. var item = items[i];
  69790. if (item.getAsEntry) {
  69791. entry = item.getAsEntry();
  69792. }
  69793. else if (item.webkitGetAsEntry) {
  69794. entry = item.webkitGetAsEntry();
  69795. }
  69796. }
  69797. if (!entry) {
  69798. files_1.push(fileToLoad);
  69799. }
  69800. else {
  69801. if (entry.isDirectory) {
  69802. folders.push(entry);
  69803. }
  69804. else {
  69805. files_1.push(fileToLoad);
  69806. }
  69807. }
  69808. }
  69809. if (folders.length === 0) {
  69810. this._processFiles(files_1);
  69811. this._processReload();
  69812. }
  69813. else {
  69814. var remaining = { count: folders.length };
  69815. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69816. var folder = folders_1[_i];
  69817. this._traverseFolder(folder, files_1, remaining, function () {
  69818. _this._processFiles(files_1);
  69819. if (remaining.count === 0) {
  69820. _this._processReload();
  69821. }
  69822. });
  69823. }
  69824. }
  69825. }
  69826. };
  69827. FilesInput.prototype._processReload = function () {
  69828. if (this._onReloadCallback) {
  69829. this._onReloadCallback(this._sceneFileToLoad);
  69830. }
  69831. else {
  69832. this.reload();
  69833. }
  69834. };
  69835. FilesInput.prototype.reload = function () {
  69836. var _this = this;
  69837. // If a scene file has been provided
  69838. if (this._sceneFileToLoad) {
  69839. if (this._currentScene) {
  69840. if (BABYLON.Tools.errorsCount > 0) {
  69841. BABYLON.Tools.ClearLogCache();
  69842. }
  69843. this._engine.stopRenderLoop();
  69844. }
  69845. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69846. if (_this._progressCallback) {
  69847. _this._progressCallback(progress);
  69848. }
  69849. }).then(function (scene) {
  69850. if (_this._currentScene) {
  69851. _this._currentScene.dispose();
  69852. }
  69853. _this._currentScene = scene;
  69854. if (_this._sceneLoadedCallback) {
  69855. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69856. }
  69857. // Wait for textures and shaders to be ready
  69858. _this._currentScene.executeWhenReady(function () {
  69859. _this._engine.runRenderLoop(function () {
  69860. _this.renderFunction();
  69861. });
  69862. });
  69863. }).catch(function (error) {
  69864. if (_this._errorCallback) {
  69865. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69866. }
  69867. });
  69868. }
  69869. else {
  69870. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69871. }
  69872. };
  69873. FilesInput.FilesToLoad = {};
  69874. return FilesInput;
  69875. }());
  69876. BABYLON.FilesInput = FilesInput;
  69877. })(BABYLON || (BABYLON = {}));
  69878. //# sourceMappingURL=babylon.filesInput.js.map
  69879. var BABYLON;
  69880. (function (BABYLON) {
  69881. var Tags = /** @class */ (function () {
  69882. function Tags() {
  69883. }
  69884. Tags.EnableFor = function (obj) {
  69885. obj._tags = obj._tags || {};
  69886. obj.hasTags = function () {
  69887. return Tags.HasTags(obj);
  69888. };
  69889. obj.addTags = function (tagsString) {
  69890. return Tags.AddTagsTo(obj, tagsString);
  69891. };
  69892. obj.removeTags = function (tagsString) {
  69893. return Tags.RemoveTagsFrom(obj, tagsString);
  69894. };
  69895. obj.matchesTagsQuery = function (tagsQuery) {
  69896. return Tags.MatchesQuery(obj, tagsQuery);
  69897. };
  69898. };
  69899. Tags.DisableFor = function (obj) {
  69900. delete obj._tags;
  69901. delete obj.hasTags;
  69902. delete obj.addTags;
  69903. delete obj.removeTags;
  69904. delete obj.matchesTagsQuery;
  69905. };
  69906. Tags.HasTags = function (obj) {
  69907. if (!obj._tags) {
  69908. return false;
  69909. }
  69910. return !BABYLON.Tools.IsEmpty(obj._tags);
  69911. };
  69912. Tags.GetTags = function (obj, asString) {
  69913. if (asString === void 0) { asString = true; }
  69914. if (!obj._tags) {
  69915. return null;
  69916. }
  69917. if (asString) {
  69918. var tagsArray = [];
  69919. for (var tag in obj._tags) {
  69920. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69921. tagsArray.push(tag);
  69922. }
  69923. }
  69924. return tagsArray.join(" ");
  69925. }
  69926. else {
  69927. return obj._tags;
  69928. }
  69929. };
  69930. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69931. // a tag cannot start with '||', '&&', and '!'
  69932. // it cannot contain whitespaces
  69933. Tags.AddTagsTo = function (obj, tagsString) {
  69934. if (!tagsString) {
  69935. return;
  69936. }
  69937. if (typeof tagsString !== "string") {
  69938. return;
  69939. }
  69940. var tags = tagsString.split(" ");
  69941. tags.forEach(function (tag, index, array) {
  69942. Tags._AddTagTo(obj, tag);
  69943. });
  69944. };
  69945. Tags._AddTagTo = function (obj, tag) {
  69946. tag = tag.trim();
  69947. if (tag === "" || tag === "true" || tag === "false") {
  69948. return;
  69949. }
  69950. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69951. return;
  69952. }
  69953. Tags.EnableFor(obj);
  69954. obj._tags[tag] = true;
  69955. };
  69956. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69957. if (!Tags.HasTags(obj)) {
  69958. return;
  69959. }
  69960. var tags = tagsString.split(" ");
  69961. for (var t in tags) {
  69962. Tags._RemoveTagFrom(obj, tags[t]);
  69963. }
  69964. };
  69965. Tags._RemoveTagFrom = function (obj, tag) {
  69966. delete obj._tags[tag];
  69967. };
  69968. Tags.MatchesQuery = function (obj, tagsQuery) {
  69969. if (tagsQuery === undefined) {
  69970. return true;
  69971. }
  69972. if (tagsQuery === "") {
  69973. return Tags.HasTags(obj);
  69974. }
  69975. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69976. };
  69977. return Tags;
  69978. }());
  69979. BABYLON.Tags = Tags;
  69980. })(BABYLON || (BABYLON = {}));
  69981. //# sourceMappingURL=babylon.tags.js.map
  69982. var BABYLON;
  69983. (function (BABYLON) {
  69984. /**
  69985. * Class used to evalaute queries containing `and` and `or` operators
  69986. */
  69987. var AndOrNotEvaluator = /** @class */ (function () {
  69988. function AndOrNotEvaluator() {
  69989. }
  69990. /**
  69991. * Evaluate a query
  69992. * @param query defines the query to evaluate
  69993. * @param evaluateCallback defines the callback used to filter result
  69994. * @returns true if the query matches
  69995. */
  69996. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69997. if (!query.match(/\([^\(\)]*\)/g)) {
  69998. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69999. }
  70000. else {
  70001. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70002. // remove parenthesis
  70003. r = r.slice(1, r.length - 1);
  70004. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70005. });
  70006. }
  70007. if (query === "true") {
  70008. return true;
  70009. }
  70010. if (query === "false") {
  70011. return false;
  70012. }
  70013. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70014. };
  70015. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70016. evaluateCallback = evaluateCallback || (function (r) {
  70017. return r === "true" ? true : false;
  70018. });
  70019. var result;
  70020. var or = parenthesisContent.split("||");
  70021. for (var i in or) {
  70022. if (or.hasOwnProperty(i)) {
  70023. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70024. var and = ori.split("&&");
  70025. if (and.length > 1) {
  70026. for (var j = 0; j < and.length; ++j) {
  70027. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70028. if (andj !== "true" && andj !== "false") {
  70029. if (andj[0] === "!") {
  70030. result = !evaluateCallback(andj.substring(1));
  70031. }
  70032. else {
  70033. result = evaluateCallback(andj);
  70034. }
  70035. }
  70036. else {
  70037. result = andj === "true" ? true : false;
  70038. }
  70039. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70040. ori = "false";
  70041. break;
  70042. }
  70043. }
  70044. }
  70045. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70046. result = true;
  70047. break;
  70048. }
  70049. // result equals false (or undefined)
  70050. if (ori !== "true" && ori !== "false") {
  70051. if (ori[0] === "!") {
  70052. result = !evaluateCallback(ori.substring(1));
  70053. }
  70054. else {
  70055. result = evaluateCallback(ori);
  70056. }
  70057. }
  70058. else {
  70059. result = ori === "true" ? true : false;
  70060. }
  70061. }
  70062. }
  70063. // the whole parenthesis scope is replaced by 'true' or 'false'
  70064. return result ? "true" : "false";
  70065. };
  70066. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70067. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70068. // remove whitespaces
  70069. r = r.replace(/[\s]/g, function () { return ""; });
  70070. return r.length % 2 ? "!" : "";
  70071. });
  70072. booleanString = booleanString.trim();
  70073. if (booleanString === "!true") {
  70074. booleanString = "false";
  70075. }
  70076. else if (booleanString === "!false") {
  70077. booleanString = "true";
  70078. }
  70079. return booleanString;
  70080. };
  70081. return AndOrNotEvaluator;
  70082. }());
  70083. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70084. })(BABYLON || (BABYLON = {}));
  70085. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70086. var BABYLON;
  70087. (function (BABYLON) {
  70088. /**
  70089. * Class used to enable access to IndexedDB
  70090. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70091. */
  70092. var Database = /** @class */ (function () {
  70093. /**
  70094. * Creates a new Database
  70095. * @param urlToScene defines the url to load the scene
  70096. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70097. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70098. */
  70099. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  70100. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  70101. var _this = this;
  70102. // Handling various flavors of prefixed version of IndexedDB
  70103. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  70104. this.callbackManifestChecked = callbackManifestChecked;
  70105. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  70106. this.db = null;
  70107. this._enableSceneOffline = false;
  70108. this._enableTexturesOffline = false;
  70109. this.manifestVersionFound = 0;
  70110. this.mustUpdateRessources = false;
  70111. this.hasReachedQuota = false;
  70112. if (!Database.IDBStorageEnabled) {
  70113. this.callbackManifestChecked(true);
  70114. }
  70115. else {
  70116. if (disableManifestCheck) {
  70117. this._enableSceneOffline = true;
  70118. this._enableTexturesOffline = true;
  70119. this.manifestVersionFound = 1;
  70120. BABYLON.Tools.SetImmediate(function () {
  70121. _this.callbackManifestChecked(true);
  70122. });
  70123. }
  70124. else {
  70125. this._checkManifestFile();
  70126. }
  70127. }
  70128. }
  70129. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  70130. /**
  70131. * Gets a boolean indicating if scene must be saved in the database
  70132. */
  70133. get: function () {
  70134. return this._enableSceneOffline;
  70135. },
  70136. enumerable: true,
  70137. configurable: true
  70138. });
  70139. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  70140. /**
  70141. * Gets a boolean indicating if textures must be saved in the database
  70142. */
  70143. get: function () {
  70144. return this._enableTexturesOffline;
  70145. },
  70146. enumerable: true,
  70147. configurable: true
  70148. });
  70149. Database.prototype._checkManifestFile = function () {
  70150. var _this = this;
  70151. var noManifestFile = function () {
  70152. _this._enableSceneOffline = false;
  70153. _this._enableTexturesOffline = false;
  70154. _this.callbackManifestChecked(false);
  70155. };
  70156. var timeStampUsed = false;
  70157. var manifestURL = this.currentSceneUrl + ".manifest";
  70158. var xhr = new XMLHttpRequest();
  70159. if (navigator.onLine) {
  70160. // Adding a timestamp to by-pass browsers' cache
  70161. timeStampUsed = true;
  70162. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  70163. }
  70164. xhr.open("GET", manifestURL, true);
  70165. xhr.addEventListener("load", function () {
  70166. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70167. try {
  70168. var manifestFile = JSON.parse(xhr.response);
  70169. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  70170. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  70171. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70172. _this.manifestVersionFound = manifestFile.version;
  70173. }
  70174. if (_this.callbackManifestChecked) {
  70175. _this.callbackManifestChecked(true);
  70176. }
  70177. }
  70178. catch (ex) {
  70179. noManifestFile();
  70180. }
  70181. }
  70182. else {
  70183. noManifestFile();
  70184. }
  70185. }, false);
  70186. xhr.addEventListener("error", function (event) {
  70187. if (timeStampUsed) {
  70188. timeStampUsed = false;
  70189. // Let's retry without the timeStamp
  70190. // It could fail when coupled with HTML5 Offline API
  70191. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  70192. xhr.open("GET", retryManifestURL, true);
  70193. xhr.send();
  70194. }
  70195. else {
  70196. noManifestFile();
  70197. }
  70198. }, false);
  70199. try {
  70200. xhr.send();
  70201. }
  70202. catch (ex) {
  70203. BABYLON.Tools.Error("Error on XHR send request.");
  70204. this.callbackManifestChecked(false);
  70205. }
  70206. };
  70207. /**
  70208. * Open the database and make it available
  70209. * @param successCallback defines the callback to call on success
  70210. * @param errorCallback defines the callback to call on error
  70211. */
  70212. Database.prototype.openAsync = function (successCallback, errorCallback) {
  70213. var _this = this;
  70214. var handleError = function () {
  70215. _this.isSupported = false;
  70216. if (errorCallback)
  70217. errorCallback();
  70218. };
  70219. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  70220. // Your browser doesn't support IndexedDB
  70221. this.isSupported = false;
  70222. if (errorCallback)
  70223. errorCallback();
  70224. }
  70225. else {
  70226. // If the DB hasn't been opened or created yet
  70227. if (!this.db) {
  70228. this.hasReachedQuota = false;
  70229. this.isSupported = true;
  70230. var request = this.idbFactory.open("babylonjs", 1);
  70231. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  70232. request.onerror = function (event) {
  70233. handleError();
  70234. };
  70235. // executes when a version change transaction cannot complete due to other active transactions
  70236. request.onblocked = function (event) {
  70237. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  70238. handleError();
  70239. };
  70240. // DB has been opened successfully
  70241. request.onsuccess = function (event) {
  70242. _this.db = request.result;
  70243. successCallback();
  70244. };
  70245. // Initialization of the DB. Creating Scenes & Textures stores
  70246. request.onupgradeneeded = function (event) {
  70247. _this.db = (event.target).result;
  70248. if (_this.db) {
  70249. try {
  70250. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  70251. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  70252. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  70253. }
  70254. catch (ex) {
  70255. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  70256. handleError();
  70257. }
  70258. }
  70259. };
  70260. }
  70261. // DB has already been created and opened
  70262. else {
  70263. if (successCallback)
  70264. successCallback();
  70265. }
  70266. }
  70267. };
  70268. /**
  70269. * Loads an image from the database
  70270. * @param url defines the url to load from
  70271. * @param image defines the target DOM image
  70272. */
  70273. Database.prototype.loadImageFromDB = function (url, image) {
  70274. var _this = this;
  70275. var completeURL = Database._ReturnFullUrlLocation(url);
  70276. var saveAndLoadImage = function () {
  70277. if (!_this.hasReachedQuota && _this.db !== null) {
  70278. // the texture is not yet in the DB, let's try to save it
  70279. _this._saveImageIntoDBAsync(completeURL, image);
  70280. }
  70281. // If the texture is not in the DB and we've reached the DB quota limit
  70282. // let's load it directly from the web
  70283. else {
  70284. image.src = url;
  70285. }
  70286. };
  70287. if (!this.mustUpdateRessources) {
  70288. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  70289. }
  70290. // First time we're download the images or update requested in the manifest file by a version change
  70291. else {
  70292. saveAndLoadImage();
  70293. }
  70294. };
  70295. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  70296. if (this.isSupported && this.db !== null) {
  70297. var texture;
  70298. var transaction = this.db.transaction(["textures"]);
  70299. transaction.onabort = function (event) {
  70300. image.src = url;
  70301. };
  70302. transaction.oncomplete = function (event) {
  70303. var blobTextureURL;
  70304. if (texture) {
  70305. var URL = window.URL || window.webkitURL;
  70306. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  70307. image.onerror = function () {
  70308. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  70309. image.src = url;
  70310. };
  70311. image.src = blobTextureURL;
  70312. }
  70313. else {
  70314. notInDBCallback();
  70315. }
  70316. };
  70317. var getRequest = transaction.objectStore("textures").get(url);
  70318. getRequest.onsuccess = function (event) {
  70319. texture = (event.target).result;
  70320. };
  70321. getRequest.onerror = function (event) {
  70322. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  70323. image.src = url;
  70324. };
  70325. }
  70326. else {
  70327. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70328. image.src = url;
  70329. }
  70330. };
  70331. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  70332. var _this = this;
  70333. if (this.isSupported) {
  70334. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  70335. var generateBlobUrl = function () {
  70336. var blobTextureURL;
  70337. if (blob) {
  70338. var URL = window.URL || window.webkitURL;
  70339. try {
  70340. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  70341. }
  70342. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  70343. catch (ex) {
  70344. blobTextureURL = URL.createObjectURL(blob);
  70345. }
  70346. }
  70347. if (blobTextureURL) {
  70348. image.src = blobTextureURL;
  70349. }
  70350. };
  70351. if (Database.IsUASupportingBlobStorage) { // Create XHR
  70352. var xhr = new XMLHttpRequest(), blob;
  70353. xhr.open("GET", url, true);
  70354. xhr.responseType = "blob";
  70355. xhr.addEventListener("load", function () {
  70356. if (xhr.status === 200 && _this.db) {
  70357. // Blob as response (XHR2)
  70358. blob = xhr.response;
  70359. var transaction = _this.db.transaction(["textures"], "readwrite");
  70360. // the transaction could abort because of a QuotaExceededError error
  70361. transaction.onabort = function (event) {
  70362. try {
  70363. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70364. var srcElement = (event.srcElement || event.target);
  70365. var error = srcElement.error;
  70366. if (error && error.name === "QuotaExceededError") {
  70367. _this.hasReachedQuota = true;
  70368. }
  70369. }
  70370. catch (ex) { }
  70371. generateBlobUrl();
  70372. };
  70373. transaction.oncomplete = function (event) {
  70374. generateBlobUrl();
  70375. };
  70376. var newTexture = { textureUrl: url, data: blob };
  70377. try {
  70378. // Put the blob into the dabase
  70379. var addRequest = transaction.objectStore("textures").put(newTexture);
  70380. addRequest.onsuccess = function (event) {
  70381. };
  70382. addRequest.onerror = function (event) {
  70383. generateBlobUrl();
  70384. };
  70385. }
  70386. catch (ex) {
  70387. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  70388. if (ex.code === 25) {
  70389. Database.IsUASupportingBlobStorage = false;
  70390. }
  70391. image.src = url;
  70392. }
  70393. }
  70394. else {
  70395. image.src = url;
  70396. }
  70397. }, false);
  70398. xhr.addEventListener("error", function (event) {
  70399. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  70400. image.src = url;
  70401. }, false);
  70402. xhr.send();
  70403. }
  70404. else {
  70405. image.src = url;
  70406. }
  70407. }
  70408. else {
  70409. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70410. image.src = url;
  70411. }
  70412. };
  70413. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  70414. var _this = this;
  70415. var updateVersion = function () {
  70416. // the version is not yet in the DB or we need to update it
  70417. _this._saveVersionIntoDBAsync(url, versionLoaded);
  70418. };
  70419. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  70420. };
  70421. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  70422. var _this = this;
  70423. if (this.isSupported && this.db) {
  70424. var version;
  70425. try {
  70426. var transaction = this.db.transaction(["versions"]);
  70427. transaction.oncomplete = function (event) {
  70428. if (version) {
  70429. // If the version in the JSON file is different from the version in DB
  70430. if (_this.manifestVersionFound !== version.data) {
  70431. _this.mustUpdateRessources = true;
  70432. updateInDBCallback();
  70433. }
  70434. else {
  70435. callback(version.data);
  70436. }
  70437. }
  70438. // version was not found in DB
  70439. else {
  70440. _this.mustUpdateRessources = true;
  70441. updateInDBCallback();
  70442. }
  70443. };
  70444. transaction.onabort = function (event) {
  70445. callback(-1);
  70446. };
  70447. var getRequest = transaction.objectStore("versions").get(url);
  70448. getRequest.onsuccess = function (event) {
  70449. version = (event.target).result;
  70450. };
  70451. getRequest.onerror = function (event) {
  70452. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  70453. callback(-1);
  70454. };
  70455. }
  70456. catch (ex) {
  70457. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  70458. callback(-1);
  70459. }
  70460. }
  70461. else {
  70462. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70463. callback(-1);
  70464. }
  70465. };
  70466. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  70467. var _this = this;
  70468. if (this.isSupported && !this.hasReachedQuota && this.db) {
  70469. try {
  70470. // Open a transaction to the database
  70471. var transaction = this.db.transaction(["versions"], "readwrite");
  70472. // the transaction could abort because of a QuotaExceededError error
  70473. transaction.onabort = function (event) {
  70474. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70475. var error = event.srcElement['error'];
  70476. if (error && error.name === "QuotaExceededError") {
  70477. _this.hasReachedQuota = true;
  70478. }
  70479. }
  70480. catch (ex) { }
  70481. callback(-1);
  70482. };
  70483. transaction.oncomplete = function (event) {
  70484. callback(_this.manifestVersionFound);
  70485. };
  70486. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  70487. // Put the scene into the database
  70488. var addRequest = transaction.objectStore("versions").put(newVersion);
  70489. addRequest.onsuccess = function (event) {
  70490. };
  70491. addRequest.onerror = function (event) {
  70492. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  70493. };
  70494. }
  70495. catch (ex) {
  70496. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70497. callback(-1);
  70498. }
  70499. }
  70500. else {
  70501. callback(-1);
  70502. }
  70503. };
  70504. /**
  70505. * Loads a file from database
  70506. * @param url defines the URL to load from
  70507. * @param sceneLoaded defines a callback to call on success
  70508. * @param progressCallBack defines a callback to call when progress changed
  70509. * @param errorCallback defines a callback to call on error
  70510. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70511. */
  70512. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70513. var _this = this;
  70514. var completeUrl = Database._ReturnFullUrlLocation(url);
  70515. var saveAndLoadFile = function () {
  70516. // the scene is not yet in the DB, let's try to save it
  70517. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70518. };
  70519. this._checkVersionFromDB(completeUrl, function (version) {
  70520. if (version !== -1) {
  70521. if (!_this.mustUpdateRessources) {
  70522. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70523. }
  70524. else {
  70525. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70526. }
  70527. }
  70528. else {
  70529. if (errorCallback) {
  70530. errorCallback();
  70531. }
  70532. }
  70533. });
  70534. };
  70535. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70536. if (this.isSupported && this.db) {
  70537. var targetStore;
  70538. if (url.indexOf(".babylon") !== -1) {
  70539. targetStore = "scenes";
  70540. }
  70541. else {
  70542. targetStore = "textures";
  70543. }
  70544. var file;
  70545. var transaction = this.db.transaction([targetStore]);
  70546. transaction.oncomplete = function (event) {
  70547. if (file) {
  70548. callback(file.data);
  70549. }
  70550. // file was not found in DB
  70551. else {
  70552. notInDBCallback();
  70553. }
  70554. };
  70555. transaction.onabort = function (event) {
  70556. notInDBCallback();
  70557. };
  70558. var getRequest = transaction.objectStore(targetStore).get(url);
  70559. getRequest.onsuccess = function (event) {
  70560. file = (event.target).result;
  70561. };
  70562. getRequest.onerror = function (event) {
  70563. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70564. notInDBCallback();
  70565. };
  70566. }
  70567. else {
  70568. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70569. callback();
  70570. }
  70571. };
  70572. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  70573. var _this = this;
  70574. if (this.isSupported) {
  70575. var targetStore;
  70576. if (url.indexOf(".babylon") !== -1) {
  70577. targetStore = "scenes";
  70578. }
  70579. else {
  70580. targetStore = "textures";
  70581. }
  70582. // Create XHR
  70583. var xhr = new XMLHttpRequest();
  70584. var fileData;
  70585. xhr.open("GET", url, true);
  70586. if (useArrayBuffer) {
  70587. xhr.responseType = "arraybuffer";
  70588. }
  70589. if (progressCallback) {
  70590. xhr.onprogress = progressCallback;
  70591. }
  70592. xhr.addEventListener("load", function () {
  70593. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  70594. // Blob as response (XHR2)
  70595. //fileData = xhr.responseText;
  70596. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70597. if (!_this.hasReachedQuota && _this.db) {
  70598. // Open a transaction to the database
  70599. var transaction = _this.db.transaction([targetStore], "readwrite");
  70600. // the transaction could abort because of a QuotaExceededError error
  70601. transaction.onabort = function (event) {
  70602. try {
  70603. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70604. var error = event.srcElement['error'];
  70605. if (error && error.name === "QuotaExceededError") {
  70606. _this.hasReachedQuota = true;
  70607. }
  70608. }
  70609. catch (ex) { }
  70610. callback(fileData);
  70611. };
  70612. transaction.oncomplete = function (event) {
  70613. callback(fileData);
  70614. };
  70615. var newFile;
  70616. if (targetStore === "scenes") {
  70617. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  70618. }
  70619. else {
  70620. newFile = { textureUrl: url, data: fileData };
  70621. }
  70622. try {
  70623. // Put the scene into the database
  70624. var addRequest = transaction.objectStore(targetStore).put(newFile);
  70625. addRequest.onsuccess = function (event) {
  70626. };
  70627. addRequest.onerror = function (event) {
  70628. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  70629. };
  70630. }
  70631. catch (ex) {
  70632. callback(fileData);
  70633. }
  70634. }
  70635. else {
  70636. callback(fileData);
  70637. }
  70638. }
  70639. else {
  70640. if (xhr.status >= 400 && errorCallback) {
  70641. errorCallback(xhr);
  70642. }
  70643. else {
  70644. callback();
  70645. }
  70646. }
  70647. }, false);
  70648. xhr.addEventListener("error", function (event) {
  70649. BABYLON.Tools.Error("error on XHR request.");
  70650. callback();
  70651. }, false);
  70652. xhr.send();
  70653. }
  70654. else {
  70655. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70656. callback();
  70657. }
  70658. };
  70659. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70660. Database.IsUASupportingBlobStorage = true;
  70661. /** Gets a boolean indicating if Database storate is enabled */
  70662. Database.IDBStorageEnabled = true;
  70663. Database._ParseURL = function (url) {
  70664. var a = document.createElement('a');
  70665. a.href = url;
  70666. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70667. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70668. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70669. return absLocation;
  70670. };
  70671. Database._ReturnFullUrlLocation = function (url) {
  70672. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70673. return (Database._ParseURL(window.location.href) + url);
  70674. }
  70675. else {
  70676. return url;
  70677. }
  70678. };
  70679. return Database;
  70680. }());
  70681. BABYLON.Database = Database;
  70682. })(BABYLON || (BABYLON = {}));
  70683. //# sourceMappingURL=babylon.database.js.map
  70684. var BABYLON;
  70685. (function (BABYLON) {
  70686. var FresnelParameters = /** @class */ (function () {
  70687. function FresnelParameters() {
  70688. this._isEnabled = true;
  70689. this.leftColor = BABYLON.Color3.White();
  70690. this.rightColor = BABYLON.Color3.Black();
  70691. this.bias = 0;
  70692. this.power = 1;
  70693. }
  70694. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70695. get: function () {
  70696. return this._isEnabled;
  70697. },
  70698. set: function (value) {
  70699. if (this._isEnabled === value) {
  70700. return;
  70701. }
  70702. this._isEnabled = value;
  70703. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70704. },
  70705. enumerable: true,
  70706. configurable: true
  70707. });
  70708. FresnelParameters.prototype.clone = function () {
  70709. var newFresnelParameters = new FresnelParameters();
  70710. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70711. return newFresnelParameters;
  70712. };
  70713. FresnelParameters.prototype.serialize = function () {
  70714. var serializationObject = {};
  70715. serializationObject.isEnabled = this.isEnabled;
  70716. serializationObject.leftColor = this.leftColor.asArray();
  70717. serializationObject.rightColor = this.rightColor.asArray();
  70718. serializationObject.bias = this.bias;
  70719. serializationObject.power = this.power;
  70720. return serializationObject;
  70721. };
  70722. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70723. var fresnelParameters = new FresnelParameters();
  70724. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70725. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70726. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70727. fresnelParameters.bias = parsedFresnelParameters.bias;
  70728. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70729. return fresnelParameters;
  70730. };
  70731. return FresnelParameters;
  70732. }());
  70733. BABYLON.FresnelParameters = FresnelParameters;
  70734. })(BABYLON || (BABYLON = {}));
  70735. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70736. var BABYLON;
  70737. (function (BABYLON) {
  70738. var MultiMaterial = /** @class */ (function (_super) {
  70739. __extends(MultiMaterial, _super);
  70740. function MultiMaterial(name, scene) {
  70741. var _this = _super.call(this, name, scene, true) || this;
  70742. scene.multiMaterials.push(_this);
  70743. _this.subMaterials = new Array();
  70744. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70745. return _this;
  70746. }
  70747. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70748. get: function () {
  70749. return this._subMaterials;
  70750. },
  70751. set: function (value) {
  70752. this._subMaterials = value;
  70753. this._hookArray(value);
  70754. },
  70755. enumerable: true,
  70756. configurable: true
  70757. });
  70758. MultiMaterial.prototype._hookArray = function (array) {
  70759. var _this = this;
  70760. var oldPush = array.push;
  70761. array.push = function () {
  70762. var items = [];
  70763. for (var _i = 0; _i < arguments.length; _i++) {
  70764. items[_i] = arguments[_i];
  70765. }
  70766. var result = oldPush.apply(array, items);
  70767. _this._markAllSubMeshesAsTexturesDirty();
  70768. return result;
  70769. };
  70770. var oldSplice = array.splice;
  70771. array.splice = function (index, deleteCount) {
  70772. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70773. _this._markAllSubMeshesAsTexturesDirty();
  70774. return deleted;
  70775. };
  70776. };
  70777. // Properties
  70778. MultiMaterial.prototype.getSubMaterial = function (index) {
  70779. if (index < 0 || index >= this.subMaterials.length) {
  70780. return this.getScene().defaultMaterial;
  70781. }
  70782. return this.subMaterials[index];
  70783. };
  70784. MultiMaterial.prototype.getActiveTextures = function () {
  70785. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70786. if (subMaterial) {
  70787. return subMaterial.getActiveTextures();
  70788. }
  70789. else {
  70790. return [];
  70791. }
  70792. }));
  70793. var _a;
  70794. };
  70795. // Methods
  70796. MultiMaterial.prototype.getClassName = function () {
  70797. return "MultiMaterial";
  70798. };
  70799. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70800. for (var index = 0; index < this.subMaterials.length; index++) {
  70801. var subMaterial = this.subMaterials[index];
  70802. if (subMaterial) {
  70803. if (subMaterial.storeEffectOnSubMeshes) {
  70804. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70805. return false;
  70806. }
  70807. continue;
  70808. }
  70809. if (!subMaterial.isReady(mesh)) {
  70810. return false;
  70811. }
  70812. }
  70813. }
  70814. return true;
  70815. };
  70816. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70817. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70818. for (var index = 0; index < this.subMaterials.length; index++) {
  70819. var subMaterial = null;
  70820. var current = this.subMaterials[index];
  70821. if (cloneChildren && current) {
  70822. subMaterial = current.clone(name + "-" + current.name);
  70823. }
  70824. else {
  70825. subMaterial = this.subMaterials[index];
  70826. }
  70827. newMultiMaterial.subMaterials.push(subMaterial);
  70828. }
  70829. return newMultiMaterial;
  70830. };
  70831. MultiMaterial.prototype.serialize = function () {
  70832. var serializationObject = {};
  70833. serializationObject.name = this.name;
  70834. serializationObject.id = this.id;
  70835. if (BABYLON.Tags) {
  70836. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70837. }
  70838. serializationObject.materials = [];
  70839. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70840. var subMat = this.subMaterials[matIndex];
  70841. if (subMat) {
  70842. serializationObject.materials.push(subMat.id);
  70843. }
  70844. else {
  70845. serializationObject.materials.push(null);
  70846. }
  70847. }
  70848. return serializationObject;
  70849. };
  70850. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70851. var scene = this.getScene();
  70852. if (!scene) {
  70853. return;
  70854. }
  70855. var index = scene.multiMaterials.indexOf(this);
  70856. if (index >= 0) {
  70857. scene.multiMaterials.splice(index, 1);
  70858. }
  70859. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70860. };
  70861. return MultiMaterial;
  70862. }(BABYLON.Material));
  70863. BABYLON.MultiMaterial = MultiMaterial;
  70864. })(BABYLON || (BABYLON = {}));
  70865. //# sourceMappingURL=babylon.multiMaterial.js.map
  70866. var BABYLON;
  70867. (function (BABYLON) {
  70868. var FreeCameraTouchInput = /** @class */ (function () {
  70869. function FreeCameraTouchInput() {
  70870. this._offsetX = null;
  70871. this._offsetY = null;
  70872. this._pointerPressed = new Array();
  70873. this.touchAngularSensibility = 200000.0;
  70874. this.touchMoveSensibility = 250.0;
  70875. }
  70876. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70877. var _this = this;
  70878. var previousPosition = null;
  70879. if (this._pointerInput === undefined) {
  70880. this._onLostFocus = function (evt) {
  70881. _this._offsetX = null;
  70882. _this._offsetY = null;
  70883. };
  70884. this._pointerInput = function (p, s) {
  70885. var evt = p.event;
  70886. if (evt.pointerType === "mouse") {
  70887. return;
  70888. }
  70889. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70890. if (!noPreventDefault) {
  70891. evt.preventDefault();
  70892. }
  70893. _this._pointerPressed.push(evt.pointerId);
  70894. if (_this._pointerPressed.length !== 1) {
  70895. return;
  70896. }
  70897. previousPosition = {
  70898. x: evt.clientX,
  70899. y: evt.clientY
  70900. };
  70901. }
  70902. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70903. if (!noPreventDefault) {
  70904. evt.preventDefault();
  70905. }
  70906. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70907. if (index === -1) {
  70908. return;
  70909. }
  70910. _this._pointerPressed.splice(index, 1);
  70911. if (index != 0) {
  70912. return;
  70913. }
  70914. previousPosition = null;
  70915. _this._offsetX = null;
  70916. _this._offsetY = null;
  70917. }
  70918. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70919. if (!noPreventDefault) {
  70920. evt.preventDefault();
  70921. }
  70922. if (!previousPosition) {
  70923. return;
  70924. }
  70925. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70926. if (index != 0) {
  70927. return;
  70928. }
  70929. _this._offsetX = evt.clientX - previousPosition.x;
  70930. _this._offsetY = -(evt.clientY - previousPosition.y);
  70931. }
  70932. };
  70933. }
  70934. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70935. if (this._onLostFocus) {
  70936. element.addEventListener("blur", this._onLostFocus);
  70937. }
  70938. };
  70939. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70940. if (this._pointerInput && element) {
  70941. if (this._observer) {
  70942. this.camera.getScene().onPointerObservable.remove(this._observer);
  70943. this._observer = null;
  70944. }
  70945. if (this._onLostFocus) {
  70946. element.removeEventListener("blur", this._onLostFocus);
  70947. this._onLostFocus = null;
  70948. }
  70949. this._pointerPressed = [];
  70950. this._offsetX = null;
  70951. this._offsetY = null;
  70952. }
  70953. };
  70954. FreeCameraTouchInput.prototype.checkInputs = function () {
  70955. if (this._offsetX && this._offsetY) {
  70956. var camera = this.camera;
  70957. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70958. if (this._pointerPressed.length > 1) {
  70959. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70960. }
  70961. else {
  70962. var speed = camera._computeLocalCameraSpeed();
  70963. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70964. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70965. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70966. }
  70967. }
  70968. };
  70969. FreeCameraTouchInput.prototype.getClassName = function () {
  70970. return "FreeCameraTouchInput";
  70971. };
  70972. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70973. return "touch";
  70974. };
  70975. __decorate([
  70976. BABYLON.serialize()
  70977. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70978. __decorate([
  70979. BABYLON.serialize()
  70980. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70981. return FreeCameraTouchInput;
  70982. }());
  70983. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70984. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70985. })(BABYLON || (BABYLON = {}));
  70986. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70987. var BABYLON;
  70988. (function (BABYLON) {
  70989. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  70990. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  70991. });
  70992. // We're mainly based on the logic defined into the FreeCamera code
  70993. var TouchCamera = /** @class */ (function (_super) {
  70994. __extends(TouchCamera, _super);
  70995. //-- end properties for backward compatibility for inputs
  70996. function TouchCamera(name, position, scene) {
  70997. var _this = _super.call(this, name, position, scene) || this;
  70998. _this.inputs.addTouch();
  70999. _this._setupInputs();
  71000. return _this;
  71001. }
  71002. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71003. //-- Begin properties for backward compatibility for inputs
  71004. get: function () {
  71005. var touch = this.inputs.attached["touch"];
  71006. if (touch)
  71007. return touch.touchAngularSensibility;
  71008. return 0;
  71009. },
  71010. set: function (value) {
  71011. var touch = this.inputs.attached["touch"];
  71012. if (touch)
  71013. touch.touchAngularSensibility = value;
  71014. },
  71015. enumerable: true,
  71016. configurable: true
  71017. });
  71018. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71019. get: function () {
  71020. var touch = this.inputs.attached["touch"];
  71021. if (touch)
  71022. return touch.touchMoveSensibility;
  71023. return 0;
  71024. },
  71025. set: function (value) {
  71026. var touch = this.inputs.attached["touch"];
  71027. if (touch)
  71028. touch.touchMoveSensibility = value;
  71029. },
  71030. enumerable: true,
  71031. configurable: true
  71032. });
  71033. TouchCamera.prototype.getClassName = function () {
  71034. return "TouchCamera";
  71035. };
  71036. TouchCamera.prototype._setupInputs = function () {
  71037. var mouse = this.inputs.attached["mouse"];
  71038. if (mouse) {
  71039. mouse.touchEnabled = false;
  71040. }
  71041. };
  71042. return TouchCamera;
  71043. }(BABYLON.FreeCamera));
  71044. BABYLON.TouchCamera = TouchCamera;
  71045. })(BABYLON || (BABYLON = {}));
  71046. //# sourceMappingURL=babylon.touchCamera.js.map
  71047. var BABYLON;
  71048. (function (BABYLON) {
  71049. var ProceduralTexture = /** @class */ (function (_super) {
  71050. __extends(ProceduralTexture, _super);
  71051. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71052. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71053. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71054. if (isCube === void 0) { isCube = false; }
  71055. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71056. _this.isCube = isCube;
  71057. _this.isEnabled = true;
  71058. _this._currentRefreshId = -1;
  71059. _this._refreshRate = 1;
  71060. _this._vertexBuffers = {};
  71061. _this._uniforms = new Array();
  71062. _this._samplers = new Array();
  71063. _this._textures = {};
  71064. _this._floats = {};
  71065. _this._floatsArrays = {};
  71066. _this._colors3 = {};
  71067. _this._colors4 = {};
  71068. _this._vectors2 = {};
  71069. _this._vectors3 = {};
  71070. _this._matrices = {};
  71071. _this._fallbackTextureUsed = false;
  71072. scene.proceduralTextures.push(_this);
  71073. _this._engine = scene.getEngine();
  71074. _this.name = name;
  71075. _this.isRenderTarget = true;
  71076. _this._size = size;
  71077. _this._generateMipMaps = generateMipMaps;
  71078. _this.setFragment(fragment);
  71079. _this._fallbackTexture = fallbackTexture;
  71080. if (isCube) {
  71081. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71082. _this.setFloat("face", 0);
  71083. }
  71084. else {
  71085. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71086. }
  71087. // VBO
  71088. var vertices = [];
  71089. vertices.push(1, 1);
  71090. vertices.push(-1, 1);
  71091. vertices.push(-1, -1);
  71092. vertices.push(1, -1);
  71093. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71094. _this._createIndexBuffer();
  71095. return _this;
  71096. }
  71097. ProceduralTexture.prototype._createIndexBuffer = function () {
  71098. var engine = this._engine;
  71099. // Indices
  71100. var indices = [];
  71101. indices.push(0);
  71102. indices.push(1);
  71103. indices.push(2);
  71104. indices.push(0);
  71105. indices.push(2);
  71106. indices.push(3);
  71107. this._indexBuffer = engine.createIndexBuffer(indices);
  71108. };
  71109. ProceduralTexture.prototype._rebuild = function () {
  71110. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71111. if (vb) {
  71112. vb._rebuild();
  71113. }
  71114. this._createIndexBuffer();
  71115. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71116. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71117. }
  71118. };
  71119. ProceduralTexture.prototype.reset = function () {
  71120. if (this._effect === undefined) {
  71121. return;
  71122. }
  71123. var engine = this._engine;
  71124. engine._releaseEffect(this._effect);
  71125. };
  71126. ProceduralTexture.prototype.isReady = function () {
  71127. var _this = this;
  71128. var engine = this._engine;
  71129. var shaders;
  71130. if (!this._fragment) {
  71131. return false;
  71132. }
  71133. if (this._fallbackTextureUsed) {
  71134. return true;
  71135. }
  71136. if (this._fragment.fragmentElement !== undefined) {
  71137. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  71138. }
  71139. else {
  71140. shaders = { vertex: "procedural", fragment: this._fragment };
  71141. }
  71142. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  71143. _this.releaseInternalTexture();
  71144. if (_this._fallbackTexture) {
  71145. _this._texture = _this._fallbackTexture._texture;
  71146. if (_this._texture) {
  71147. _this._texture.incrementReferences();
  71148. }
  71149. }
  71150. _this._fallbackTextureUsed = true;
  71151. });
  71152. return this._effect.isReady();
  71153. };
  71154. ProceduralTexture.prototype.resetRefreshCounter = function () {
  71155. this._currentRefreshId = -1;
  71156. };
  71157. ProceduralTexture.prototype.setFragment = function (fragment) {
  71158. this._fragment = fragment;
  71159. };
  71160. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  71161. get: function () {
  71162. return this._refreshRate;
  71163. },
  71164. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71165. set: function (value) {
  71166. this._refreshRate = value;
  71167. this.resetRefreshCounter();
  71168. },
  71169. enumerable: true,
  71170. configurable: true
  71171. });
  71172. ProceduralTexture.prototype._shouldRender = function () {
  71173. if (!this.isEnabled || !this.isReady() || !this._texture) {
  71174. return false;
  71175. }
  71176. if (this._fallbackTextureUsed) {
  71177. return false;
  71178. }
  71179. if (this._currentRefreshId === -1) { // At least render once
  71180. this._currentRefreshId = 1;
  71181. return true;
  71182. }
  71183. if (this.refreshRate === this._currentRefreshId) {
  71184. this._currentRefreshId = 1;
  71185. return true;
  71186. }
  71187. this._currentRefreshId++;
  71188. return false;
  71189. };
  71190. ProceduralTexture.prototype.getRenderSize = function () {
  71191. return this._size;
  71192. };
  71193. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  71194. if (this._fallbackTextureUsed) {
  71195. return;
  71196. }
  71197. this.releaseInternalTexture();
  71198. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  71199. // Update properties
  71200. this._size = size;
  71201. this._generateMipMaps = generateMipMaps;
  71202. };
  71203. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  71204. if (this._uniforms.indexOf(uniformName) === -1) {
  71205. this._uniforms.push(uniformName);
  71206. }
  71207. };
  71208. ProceduralTexture.prototype.setTexture = function (name, texture) {
  71209. if (this._samplers.indexOf(name) === -1) {
  71210. this._samplers.push(name);
  71211. }
  71212. this._textures[name] = texture;
  71213. return this;
  71214. };
  71215. ProceduralTexture.prototype.setFloat = function (name, value) {
  71216. this._checkUniform(name);
  71217. this._floats[name] = value;
  71218. return this;
  71219. };
  71220. ProceduralTexture.prototype.setFloats = function (name, value) {
  71221. this._checkUniform(name);
  71222. this._floatsArrays[name] = value;
  71223. return this;
  71224. };
  71225. ProceduralTexture.prototype.setColor3 = function (name, value) {
  71226. this._checkUniform(name);
  71227. this._colors3[name] = value;
  71228. return this;
  71229. };
  71230. ProceduralTexture.prototype.setColor4 = function (name, value) {
  71231. this._checkUniform(name);
  71232. this._colors4[name] = value;
  71233. return this;
  71234. };
  71235. ProceduralTexture.prototype.setVector2 = function (name, value) {
  71236. this._checkUniform(name);
  71237. this._vectors2[name] = value;
  71238. return this;
  71239. };
  71240. ProceduralTexture.prototype.setVector3 = function (name, value) {
  71241. this._checkUniform(name);
  71242. this._vectors3[name] = value;
  71243. return this;
  71244. };
  71245. ProceduralTexture.prototype.setMatrix = function (name, value) {
  71246. this._checkUniform(name);
  71247. this._matrices[name] = value;
  71248. return this;
  71249. };
  71250. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71251. var scene = this.getScene();
  71252. if (!scene) {
  71253. return;
  71254. }
  71255. var engine = this._engine;
  71256. // Render
  71257. engine.enableEffect(this._effect);
  71258. engine.setState(false);
  71259. // Texture
  71260. for (var name in this._textures) {
  71261. this._effect.setTexture(name, this._textures[name]);
  71262. }
  71263. // Float
  71264. for (name in this._floats) {
  71265. this._effect.setFloat(name, this._floats[name]);
  71266. }
  71267. // Floats
  71268. for (name in this._floatsArrays) {
  71269. this._effect.setArray(name, this._floatsArrays[name]);
  71270. }
  71271. // Color3
  71272. for (name in this._colors3) {
  71273. this._effect.setColor3(name, this._colors3[name]);
  71274. }
  71275. // Color4
  71276. for (name in this._colors4) {
  71277. var color = this._colors4[name];
  71278. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  71279. }
  71280. // Vector2
  71281. for (name in this._vectors2) {
  71282. this._effect.setVector2(name, this._vectors2[name]);
  71283. }
  71284. // Vector3
  71285. for (name in this._vectors3) {
  71286. this._effect.setVector3(name, this._vectors3[name]);
  71287. }
  71288. // Matrix
  71289. for (name in this._matrices) {
  71290. this._effect.setMatrix(name, this._matrices[name]);
  71291. }
  71292. if (!this._texture) {
  71293. return;
  71294. }
  71295. if (this.isCube) {
  71296. for (var face = 0; face < 6; face++) {
  71297. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  71298. // VBOs
  71299. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71300. this._effect.setFloat("face", face);
  71301. // Clear
  71302. engine.clear(scene.clearColor, true, true, true);
  71303. // Draw order
  71304. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71305. // Mipmaps
  71306. if (face === 5) {
  71307. engine.generateMipMapsForCubemap(this._texture);
  71308. }
  71309. }
  71310. }
  71311. else {
  71312. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  71313. // VBOs
  71314. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71315. // Clear
  71316. engine.clear(scene.clearColor, true, true, true);
  71317. // Draw order
  71318. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71319. }
  71320. // Unbind
  71321. engine.unBindFramebuffer(this._texture, this.isCube);
  71322. if (this.onGenerated) {
  71323. this.onGenerated();
  71324. }
  71325. };
  71326. ProceduralTexture.prototype.clone = function () {
  71327. var textureSize = this.getSize();
  71328. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  71329. // Base texture
  71330. newTexture.hasAlpha = this.hasAlpha;
  71331. newTexture.level = this.level;
  71332. // RenderTarget Texture
  71333. newTexture.coordinatesMode = this.coordinatesMode;
  71334. return newTexture;
  71335. };
  71336. ProceduralTexture.prototype.dispose = function () {
  71337. var scene = this.getScene();
  71338. if (!scene) {
  71339. return;
  71340. }
  71341. var index = scene.proceduralTextures.indexOf(this);
  71342. if (index >= 0) {
  71343. scene.proceduralTextures.splice(index, 1);
  71344. }
  71345. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71346. if (vertexBuffer) {
  71347. vertexBuffer.dispose();
  71348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71349. }
  71350. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  71351. this._indexBuffer = null;
  71352. }
  71353. _super.prototype.dispose.call(this);
  71354. };
  71355. __decorate([
  71356. BABYLON.serialize()
  71357. ], ProceduralTexture.prototype, "_size", void 0);
  71358. __decorate([
  71359. BABYLON.serialize()
  71360. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  71361. __decorate([
  71362. BABYLON.serialize()
  71363. ], ProceduralTexture.prototype, "isEnabled", void 0);
  71364. __decorate([
  71365. BABYLON.serialize()
  71366. ], ProceduralTexture.prototype, "refreshRate", null);
  71367. return ProceduralTexture;
  71368. }(BABYLON.Texture));
  71369. BABYLON.ProceduralTexture = ProceduralTexture;
  71370. })(BABYLON || (BABYLON = {}));
  71371. //# sourceMappingURL=babylon.proceduralTexture.js.map
  71372. var BABYLON;
  71373. (function (BABYLON) {
  71374. var CustomProceduralTexture = /** @class */ (function (_super) {
  71375. __extends(CustomProceduralTexture, _super);
  71376. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  71377. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  71378. _this._animate = true;
  71379. _this._time = 0;
  71380. _this._texturePath = texturePath;
  71381. //Try to load json
  71382. _this.loadJson(texturePath);
  71383. _this.refreshRate = 1;
  71384. return _this;
  71385. }
  71386. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  71387. var _this = this;
  71388. var noConfigFile = function () {
  71389. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  71390. try {
  71391. _this.setFragment(_this._texturePath);
  71392. }
  71393. catch (ex) {
  71394. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  71395. }
  71396. };
  71397. var configFileUrl = jsonUrl + "/config.json";
  71398. var xhr = new XMLHttpRequest();
  71399. xhr.open("GET", configFileUrl, true);
  71400. xhr.addEventListener("load", function () {
  71401. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71402. try {
  71403. _this._config = JSON.parse(xhr.response);
  71404. _this.updateShaderUniforms();
  71405. _this.updateTextures();
  71406. _this.setFragment(_this._texturePath + "/custom");
  71407. _this._animate = _this._config.animate;
  71408. _this.refreshRate = _this._config.refreshrate;
  71409. }
  71410. catch (ex) {
  71411. noConfigFile();
  71412. }
  71413. }
  71414. else {
  71415. noConfigFile();
  71416. }
  71417. }, false);
  71418. xhr.addEventListener("error", function () {
  71419. noConfigFile();
  71420. }, false);
  71421. try {
  71422. xhr.send();
  71423. }
  71424. catch (ex) {
  71425. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  71426. }
  71427. };
  71428. CustomProceduralTexture.prototype.isReady = function () {
  71429. if (!_super.prototype.isReady.call(this)) {
  71430. return false;
  71431. }
  71432. for (var name in this._textures) {
  71433. var texture = this._textures[name];
  71434. if (!texture.isReady()) {
  71435. return false;
  71436. }
  71437. }
  71438. return true;
  71439. };
  71440. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71441. var scene = this.getScene();
  71442. if (this._animate && scene) {
  71443. this._time += scene.getAnimationRatio() * 0.03;
  71444. this.updateShaderUniforms();
  71445. }
  71446. _super.prototype.render.call(this, useCameraPostProcess);
  71447. };
  71448. CustomProceduralTexture.prototype.updateTextures = function () {
  71449. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  71450. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  71451. }
  71452. };
  71453. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  71454. if (this._config) {
  71455. for (var j = 0; j < this._config.uniforms.length; j++) {
  71456. var uniform = this._config.uniforms[j];
  71457. switch (uniform.type) {
  71458. case "float":
  71459. this.setFloat(uniform.name, uniform.value);
  71460. break;
  71461. case "color3":
  71462. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  71463. break;
  71464. case "color4":
  71465. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  71466. break;
  71467. case "vector2":
  71468. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  71469. break;
  71470. case "vector3":
  71471. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  71472. break;
  71473. }
  71474. }
  71475. }
  71476. this.setFloat("time", this._time);
  71477. };
  71478. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  71479. get: function () {
  71480. return this._animate;
  71481. },
  71482. set: function (value) {
  71483. this._animate = value;
  71484. },
  71485. enumerable: true,
  71486. configurable: true
  71487. });
  71488. return CustomProceduralTexture;
  71489. }(BABYLON.ProceduralTexture));
  71490. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  71491. })(BABYLON || (BABYLON = {}));
  71492. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  71493. var BABYLON;
  71494. (function (BABYLON) {
  71495. var FreeCameraGamepadInput = /** @class */ (function () {
  71496. function FreeCameraGamepadInput() {
  71497. this.gamepadAngularSensibility = 200;
  71498. this.gamepadMoveSensibility = 40;
  71499. // private members
  71500. this._cameraTransform = BABYLON.Matrix.Identity();
  71501. this._deltaTransform = BABYLON.Vector3.Zero();
  71502. this._vector3 = BABYLON.Vector3.Zero();
  71503. this._vector2 = BABYLON.Vector2.Zero();
  71504. }
  71505. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71506. var _this = this;
  71507. var manager = this.camera.getScene().gamepadManager;
  71508. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71509. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71510. // prioritize XBOX gamepads.
  71511. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71512. _this.gamepad = gamepad;
  71513. }
  71514. }
  71515. });
  71516. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71517. if (_this.gamepad === gamepad) {
  71518. _this.gamepad = null;
  71519. }
  71520. });
  71521. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71522. };
  71523. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71524. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71525. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71526. this.gamepad = null;
  71527. };
  71528. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71529. if (this.gamepad && this.gamepad.leftStick) {
  71530. var camera = this.camera;
  71531. var LSValues = this.gamepad.leftStick;
  71532. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71533. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71534. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71535. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71536. var RSValues = this.gamepad.rightStick;
  71537. if (RSValues) {
  71538. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71539. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71540. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71541. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71542. }
  71543. else {
  71544. RSValues = { x: 0, y: 0 };
  71545. }
  71546. if (!camera.rotationQuaternion) {
  71547. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71548. }
  71549. else {
  71550. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71551. }
  71552. var speed = camera._computeLocalCameraSpeed() * 50.0;
  71553. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  71554. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  71555. camera.cameraDirection.addInPlace(this._deltaTransform);
  71556. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  71557. camera.cameraRotation.addInPlace(this._vector2);
  71558. }
  71559. };
  71560. FreeCameraGamepadInput.prototype.getClassName = function () {
  71561. return "FreeCameraGamepadInput";
  71562. };
  71563. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  71564. return "gamepad";
  71565. };
  71566. __decorate([
  71567. BABYLON.serialize()
  71568. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  71569. __decorate([
  71570. BABYLON.serialize()
  71571. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71572. return FreeCameraGamepadInput;
  71573. }());
  71574. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71575. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71576. })(BABYLON || (BABYLON = {}));
  71577. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71578. var BABYLON;
  71579. (function (BABYLON) {
  71580. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71581. function ArcRotateCameraGamepadInput() {
  71582. this.gamepadRotationSensibility = 80;
  71583. this.gamepadMoveSensibility = 40;
  71584. }
  71585. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71586. var _this = this;
  71587. var manager = this.camera.getScene().gamepadManager;
  71588. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71589. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71590. // prioritize XBOX gamepads.
  71591. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71592. _this.gamepad = gamepad;
  71593. }
  71594. }
  71595. });
  71596. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71597. if (_this.gamepad === gamepad) {
  71598. _this.gamepad = null;
  71599. }
  71600. });
  71601. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71602. };
  71603. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  71604. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71605. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71606. this.gamepad = null;
  71607. };
  71608. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  71609. if (this.gamepad) {
  71610. var camera = this.camera;
  71611. var RSValues = this.gamepad.rightStick;
  71612. if (RSValues) {
  71613. if (RSValues.x != 0) {
  71614. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  71615. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  71616. camera.inertialAlphaOffset += normalizedRX;
  71617. }
  71618. }
  71619. if (RSValues.y != 0) {
  71620. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  71621. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  71622. camera.inertialBetaOffset += normalizedRY;
  71623. }
  71624. }
  71625. }
  71626. var LSValues = this.gamepad.leftStick;
  71627. if (LSValues && LSValues.y != 0) {
  71628. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71629. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  71630. this.camera.inertialRadiusOffset -= normalizedLY;
  71631. }
  71632. }
  71633. }
  71634. };
  71635. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  71636. return "ArcRotateCameraGamepadInput";
  71637. };
  71638. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  71639. return "gamepad";
  71640. };
  71641. __decorate([
  71642. BABYLON.serialize()
  71643. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  71644. __decorate([
  71645. BABYLON.serialize()
  71646. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71647. return ArcRotateCameraGamepadInput;
  71648. }());
  71649. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  71650. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  71651. })(BABYLON || (BABYLON = {}));
  71652. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  71653. var BABYLON;
  71654. (function (BABYLON) {
  71655. var GamepadManager = /** @class */ (function () {
  71656. function GamepadManager(_scene) {
  71657. var _this = this;
  71658. this._scene = _scene;
  71659. this._babylonGamepads = [];
  71660. this._oneGamepadConnected = false;
  71661. this._isMonitoring = false;
  71662. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71663. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71664. this._gamepadEventSupported = false;
  71665. }
  71666. else {
  71667. this._gamepadEventSupported = 'GamepadEvent' in window;
  71668. this._gamepadSupport = (navigator.getGamepads ||
  71669. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71670. }
  71671. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71672. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71673. for (var i in _this._babylonGamepads) {
  71674. var gamepad = _this._babylonGamepads[i];
  71675. if (gamepad && gamepad._isConnected) {
  71676. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71677. }
  71678. }
  71679. });
  71680. this._onGamepadConnectedEvent = function (evt) {
  71681. var gamepad = evt.gamepad;
  71682. if (gamepad.index in _this._babylonGamepads) {
  71683. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71684. return;
  71685. }
  71686. }
  71687. var newGamepad;
  71688. if (_this._babylonGamepads[gamepad.index]) {
  71689. newGamepad = _this._babylonGamepads[gamepad.index];
  71690. newGamepad.browserGamepad = gamepad;
  71691. newGamepad._isConnected = true;
  71692. }
  71693. else {
  71694. newGamepad = _this._addNewGamepad(gamepad);
  71695. }
  71696. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71697. _this._startMonitoringGamepads();
  71698. };
  71699. this._onGamepadDisconnectedEvent = function (evt) {
  71700. var gamepad = evt.gamepad;
  71701. // Remove the gamepad from the list of gamepads to monitor.
  71702. for (var i in _this._babylonGamepads) {
  71703. if (_this._babylonGamepads[i].index === gamepad.index) {
  71704. var disconnectedGamepad = _this._babylonGamepads[i];
  71705. disconnectedGamepad._isConnected = false;
  71706. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71707. break;
  71708. }
  71709. }
  71710. };
  71711. if (this._gamepadSupport) {
  71712. //first add already-connected gamepads
  71713. this._updateGamepadObjects();
  71714. if (this._babylonGamepads.length) {
  71715. this._startMonitoringGamepads();
  71716. }
  71717. // Checking if the gamepad connected event is supported (like in Firefox)
  71718. if (this._gamepadEventSupported) {
  71719. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71720. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71721. }
  71722. else {
  71723. this._startMonitoringGamepads();
  71724. }
  71725. }
  71726. }
  71727. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71728. get: function () {
  71729. return this._babylonGamepads;
  71730. },
  71731. enumerable: true,
  71732. configurable: true
  71733. });
  71734. GamepadManager.prototype.getGamepadByType = function (type) {
  71735. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71736. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71737. var gamepad = _a[_i];
  71738. if (gamepad && gamepad.type === type) {
  71739. return gamepad;
  71740. }
  71741. }
  71742. return null;
  71743. };
  71744. GamepadManager.prototype.dispose = function () {
  71745. if (this._gamepadEventSupported) {
  71746. if (this._onGamepadConnectedEvent) {
  71747. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71748. }
  71749. if (this._onGamepadDisconnectedEvent) {
  71750. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71751. }
  71752. this._onGamepadConnectedEvent = null;
  71753. this._onGamepadDisconnectedEvent = null;
  71754. }
  71755. this._babylonGamepads.forEach(function (gamepad) {
  71756. gamepad.dispose();
  71757. });
  71758. this.onGamepadConnectedObservable.clear();
  71759. this.onGamepadDisconnectedObservable.clear();
  71760. this._oneGamepadConnected = false;
  71761. this._stopMonitoringGamepads();
  71762. this._babylonGamepads = [];
  71763. };
  71764. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71765. if (!this._oneGamepadConnected) {
  71766. this._oneGamepadConnected = true;
  71767. }
  71768. var newGamepad;
  71769. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71770. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71771. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71772. }
  71773. // if pose is supported, use the (WebVR) pose enabled controller
  71774. else if (gamepad.pose) {
  71775. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71776. }
  71777. else {
  71778. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71779. }
  71780. this._babylonGamepads[newGamepad.index] = newGamepad;
  71781. return newGamepad;
  71782. };
  71783. GamepadManager.prototype._startMonitoringGamepads = function () {
  71784. if (!this._isMonitoring) {
  71785. this._isMonitoring = true;
  71786. //back-comp
  71787. if (!this._scene) {
  71788. this._checkGamepadsStatus();
  71789. }
  71790. }
  71791. };
  71792. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71793. this._isMonitoring = false;
  71794. };
  71795. GamepadManager.prototype._checkGamepadsStatus = function () {
  71796. var _this = this;
  71797. // Hack to be compatible Chrome
  71798. this._updateGamepadObjects();
  71799. for (var i in this._babylonGamepads) {
  71800. var gamepad = this._babylonGamepads[i];
  71801. if (!gamepad || !gamepad.isConnected) {
  71802. continue;
  71803. }
  71804. gamepad.update();
  71805. }
  71806. if (this._isMonitoring && !this._scene) {
  71807. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71808. }
  71809. };
  71810. // This function is called only on Chrome, which does not properly support
  71811. // connection/disconnection events and forces you to recopy again the gamepad object
  71812. GamepadManager.prototype._updateGamepadObjects = function () {
  71813. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71814. for (var i = 0; i < gamepads.length; i++) {
  71815. var gamepad = gamepads[i];
  71816. if (gamepad) {
  71817. if (!this._babylonGamepads[gamepad.index]) {
  71818. var newGamepad = this._addNewGamepad(gamepad);
  71819. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71820. }
  71821. else {
  71822. // Forced to copy again this object for Chrome for unknown reason
  71823. this._babylonGamepads[i].browserGamepad = gamepad;
  71824. if (!this._babylonGamepads[i].isConnected) {
  71825. this._babylonGamepads[i]._isConnected = true;
  71826. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71827. }
  71828. }
  71829. }
  71830. }
  71831. };
  71832. return GamepadManager;
  71833. }());
  71834. BABYLON.GamepadManager = GamepadManager;
  71835. })(BABYLON || (BABYLON = {}));
  71836. //# sourceMappingURL=babylon.gamepadManager.js.map
  71837. var BABYLON;
  71838. (function (BABYLON) {
  71839. var StickValues = /** @class */ (function () {
  71840. function StickValues(x, y) {
  71841. this.x = x;
  71842. this.y = y;
  71843. }
  71844. return StickValues;
  71845. }());
  71846. BABYLON.StickValues = StickValues;
  71847. var Gamepad = /** @class */ (function () {
  71848. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71849. if (leftStickX === void 0) { leftStickX = 0; }
  71850. if (leftStickY === void 0) { leftStickY = 1; }
  71851. if (rightStickX === void 0) { rightStickX = 2; }
  71852. if (rightStickY === void 0) { rightStickY = 3; }
  71853. this.id = id;
  71854. this.index = index;
  71855. this.browserGamepad = browserGamepad;
  71856. this._isConnected = true;
  71857. this._invertLeftStickY = false;
  71858. this.type = Gamepad.GAMEPAD;
  71859. this._leftStickAxisX = leftStickX;
  71860. this._leftStickAxisY = leftStickY;
  71861. this._rightStickAxisX = rightStickX;
  71862. this._rightStickAxisY = rightStickY;
  71863. if (this.browserGamepad.axes.length >= 2) {
  71864. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71865. }
  71866. if (this.browserGamepad.axes.length >= 4) {
  71867. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71868. }
  71869. }
  71870. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71871. get: function () {
  71872. return this._isConnected;
  71873. },
  71874. enumerable: true,
  71875. configurable: true
  71876. });
  71877. Gamepad.prototype.onleftstickchanged = function (callback) {
  71878. this._onleftstickchanged = callback;
  71879. };
  71880. Gamepad.prototype.onrightstickchanged = function (callback) {
  71881. this._onrightstickchanged = callback;
  71882. };
  71883. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71884. get: function () {
  71885. return this._leftStick;
  71886. },
  71887. set: function (newValues) {
  71888. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71889. this._onleftstickchanged(newValues);
  71890. }
  71891. this._leftStick = newValues;
  71892. },
  71893. enumerable: true,
  71894. configurable: true
  71895. });
  71896. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71897. get: function () {
  71898. return this._rightStick;
  71899. },
  71900. set: function (newValues) {
  71901. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71902. this._onrightstickchanged(newValues);
  71903. }
  71904. this._rightStick = newValues;
  71905. },
  71906. enumerable: true,
  71907. configurable: true
  71908. });
  71909. Gamepad.prototype.update = function () {
  71910. if (this._leftStick) {
  71911. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71912. if (this._invertLeftStickY) {
  71913. this.leftStick.y *= -1;
  71914. }
  71915. }
  71916. if (this._rightStick) {
  71917. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71918. }
  71919. };
  71920. Gamepad.prototype.dispose = function () {
  71921. };
  71922. Gamepad.GAMEPAD = 0;
  71923. Gamepad.GENERIC = 1;
  71924. Gamepad.XBOX = 2;
  71925. Gamepad.POSE_ENABLED = 3;
  71926. return Gamepad;
  71927. }());
  71928. BABYLON.Gamepad = Gamepad;
  71929. var GenericPad = /** @class */ (function (_super) {
  71930. __extends(GenericPad, _super);
  71931. function GenericPad(id, index, browserGamepad) {
  71932. var _this = _super.call(this, id, index, browserGamepad) || this;
  71933. _this.onButtonDownObservable = new BABYLON.Observable();
  71934. _this.onButtonUpObservable = new BABYLON.Observable();
  71935. _this.type = Gamepad.GENERIC;
  71936. _this._buttons = new Array(browserGamepad.buttons.length);
  71937. return _this;
  71938. }
  71939. GenericPad.prototype.onbuttondown = function (callback) {
  71940. this._onbuttondown = callback;
  71941. };
  71942. GenericPad.prototype.onbuttonup = function (callback) {
  71943. this._onbuttonup = callback;
  71944. };
  71945. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71946. if (newValue !== currentValue) {
  71947. if (newValue === 1) {
  71948. if (this._onbuttondown) {
  71949. this._onbuttondown(buttonIndex);
  71950. }
  71951. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71952. }
  71953. if (newValue === 0) {
  71954. if (this._onbuttonup) {
  71955. this._onbuttonup(buttonIndex);
  71956. }
  71957. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71958. }
  71959. }
  71960. return newValue;
  71961. };
  71962. GenericPad.prototype.update = function () {
  71963. _super.prototype.update.call(this);
  71964. for (var index = 0; index < this._buttons.length; index++) {
  71965. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71966. }
  71967. };
  71968. GenericPad.prototype.dispose = function () {
  71969. _super.prototype.dispose.call(this);
  71970. this.onButtonDownObservable.clear();
  71971. this.onButtonUpObservable.clear();
  71972. };
  71973. return GenericPad;
  71974. }(Gamepad));
  71975. BABYLON.GenericPad = GenericPad;
  71976. })(BABYLON || (BABYLON = {}));
  71977. //# sourceMappingURL=babylon.gamepad.js.map
  71978. var BABYLON;
  71979. (function (BABYLON) {
  71980. /**
  71981. * Defines supported buttons for XBox360 compatible gamepads
  71982. */
  71983. var Xbox360Button;
  71984. (function (Xbox360Button) {
  71985. /** A */
  71986. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71987. /** B */
  71988. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71989. /** X */
  71990. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71991. /** Y */
  71992. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71993. /** Start */
  71994. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71995. /** Back */
  71996. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71997. /** Left button */
  71998. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71999. /** Right button */
  72000. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72001. /** Left stick */
  72002. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72003. /** Right stick */
  72004. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72005. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72006. /** Defines values for XBox360 DPad */
  72007. var Xbox360Dpad;
  72008. (function (Xbox360Dpad) {
  72009. /** Up */
  72010. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72011. /** Down */
  72012. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72013. /** Left */
  72014. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72015. /** Right */
  72016. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72017. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72018. /**
  72019. * Defines a XBox360 gamepad
  72020. */
  72021. var Xbox360Pad = /** @class */ (function (_super) {
  72022. __extends(Xbox360Pad, _super);
  72023. /**
  72024. * Creates a new XBox360 gamepad object
  72025. * @param id defines the id of this gamepad
  72026. * @param index defines its index
  72027. * @param gamepad defines the internal HTML gamepad object
  72028. * @param xboxOne defines if it is a XBox One gamepad
  72029. */
  72030. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72031. if (xboxOne === void 0) { xboxOne = false; }
  72032. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72033. _this._leftTrigger = 0;
  72034. _this._rightTrigger = 0;
  72035. /** Observable raised when a button is pressed */
  72036. _this.onButtonDownObservable = new BABYLON.Observable();
  72037. /** Observable raised when a button is released */
  72038. _this.onButtonUpObservable = new BABYLON.Observable();
  72039. /** Observable raised when a pad is pressed */
  72040. _this.onPadDownObservable = new BABYLON.Observable();
  72041. /** Observable raised when a pad is released */
  72042. _this.onPadUpObservable = new BABYLON.Observable();
  72043. _this._buttonA = 0;
  72044. _this._buttonB = 0;
  72045. _this._buttonX = 0;
  72046. _this._buttonY = 0;
  72047. _this._buttonBack = 0;
  72048. _this._buttonStart = 0;
  72049. _this._buttonLB = 0;
  72050. _this._buttonRB = 0;
  72051. _this._buttonLeftStick = 0;
  72052. _this._buttonRightStick = 0;
  72053. _this._dPadUp = 0;
  72054. _this._dPadDown = 0;
  72055. _this._dPadLeft = 0;
  72056. _this._dPadRight = 0;
  72057. _this._isXboxOnePad = false;
  72058. _this.type = BABYLON.Gamepad.XBOX;
  72059. _this._isXboxOnePad = xboxOne;
  72060. return _this;
  72061. }
  72062. /**
  72063. * Defines the callback to call when left trigger is pressed
  72064. * @param callback defines the callback to use
  72065. */
  72066. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72067. this._onlefttriggerchanged = callback;
  72068. };
  72069. /**
  72070. * Defines the callback to call when right trigger is pressed
  72071. * @param callback defines the callback to use
  72072. */
  72073. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72074. this._onrighttriggerchanged = callback;
  72075. };
  72076. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72077. /**
  72078. * Gets or sets left trigger value
  72079. */
  72080. get: function () {
  72081. return this._leftTrigger;
  72082. },
  72083. set: function (newValue) {
  72084. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  72085. this._onlefttriggerchanged(newValue);
  72086. }
  72087. this._leftTrigger = newValue;
  72088. },
  72089. enumerable: true,
  72090. configurable: true
  72091. });
  72092. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  72093. /**
  72094. * Gets or sets right trigger value
  72095. */
  72096. get: function () {
  72097. return this._rightTrigger;
  72098. },
  72099. set: function (newValue) {
  72100. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  72101. this._onrighttriggerchanged(newValue);
  72102. }
  72103. this._rightTrigger = newValue;
  72104. },
  72105. enumerable: true,
  72106. configurable: true
  72107. });
  72108. /**
  72109. * Defines the callback to call when a button is pressed
  72110. * @param callback defines the callback to use
  72111. */
  72112. Xbox360Pad.prototype.onbuttondown = function (callback) {
  72113. this._onbuttondown = callback;
  72114. };
  72115. /**
  72116. * Defines the callback to call when a button is released
  72117. * @param callback defines the callback to use
  72118. */
  72119. Xbox360Pad.prototype.onbuttonup = function (callback) {
  72120. this._onbuttonup = callback;
  72121. };
  72122. /**
  72123. * Defines the callback to call when a pad is pressed
  72124. * @param callback defines the callback to use
  72125. */
  72126. Xbox360Pad.prototype.ondpaddown = function (callback) {
  72127. this._ondpaddown = callback;
  72128. };
  72129. /**
  72130. * Defines the callback to call when a pad is released
  72131. * @param callback defines the callback to use
  72132. */
  72133. Xbox360Pad.prototype.ondpadup = function (callback) {
  72134. this._ondpadup = callback;
  72135. };
  72136. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  72137. if (newValue !== currentValue) {
  72138. if (newValue === 1) {
  72139. if (this._onbuttondown) {
  72140. this._onbuttondown(buttonType);
  72141. }
  72142. this.onButtonDownObservable.notifyObservers(buttonType);
  72143. }
  72144. if (newValue === 0) {
  72145. if (this._onbuttonup) {
  72146. this._onbuttonup(buttonType);
  72147. }
  72148. this.onButtonUpObservable.notifyObservers(buttonType);
  72149. }
  72150. }
  72151. return newValue;
  72152. };
  72153. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  72154. if (newValue !== currentValue) {
  72155. if (newValue === 1) {
  72156. if (this._ondpaddown) {
  72157. this._ondpaddown(buttonType);
  72158. }
  72159. this.onPadDownObservable.notifyObservers(buttonType);
  72160. }
  72161. if (newValue === 0) {
  72162. if (this._ondpadup) {
  72163. this._ondpadup(buttonType);
  72164. }
  72165. this.onPadUpObservable.notifyObservers(buttonType);
  72166. }
  72167. }
  72168. return newValue;
  72169. };
  72170. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  72171. /** Gets or sets value of A button */
  72172. get: function () {
  72173. return this._buttonA;
  72174. },
  72175. set: function (value) {
  72176. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  72177. },
  72178. enumerable: true,
  72179. configurable: true
  72180. });
  72181. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  72182. /** Gets or sets value of B button */
  72183. get: function () {
  72184. return this._buttonB;
  72185. },
  72186. set: function (value) {
  72187. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  72188. },
  72189. enumerable: true,
  72190. configurable: true
  72191. });
  72192. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  72193. /** Gets or sets value of X button */
  72194. get: function () {
  72195. return this._buttonX;
  72196. },
  72197. set: function (value) {
  72198. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  72199. },
  72200. enumerable: true,
  72201. configurable: true
  72202. });
  72203. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  72204. /** Gets or sets value of Y button */
  72205. get: function () {
  72206. return this._buttonY;
  72207. },
  72208. set: function (value) {
  72209. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  72210. },
  72211. enumerable: true,
  72212. configurable: true
  72213. });
  72214. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  72215. /** Gets or sets value of Start button */
  72216. get: function () {
  72217. return this._buttonStart;
  72218. },
  72219. set: function (value) {
  72220. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  72221. },
  72222. enumerable: true,
  72223. configurable: true
  72224. });
  72225. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  72226. /** Gets or sets value of Back button */
  72227. get: function () {
  72228. return this._buttonBack;
  72229. },
  72230. set: function (value) {
  72231. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  72232. },
  72233. enumerable: true,
  72234. configurable: true
  72235. });
  72236. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  72237. /** Gets or sets value of Left button */
  72238. get: function () {
  72239. return this._buttonLB;
  72240. },
  72241. set: function (value) {
  72242. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  72243. },
  72244. enumerable: true,
  72245. configurable: true
  72246. });
  72247. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  72248. /** Gets or sets value of Right button */
  72249. get: function () {
  72250. return this._buttonRB;
  72251. },
  72252. set: function (value) {
  72253. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  72254. },
  72255. enumerable: true,
  72256. configurable: true
  72257. });
  72258. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  72259. /** Gets or sets value of left stick */
  72260. get: function () {
  72261. return this._buttonLeftStick;
  72262. },
  72263. set: function (value) {
  72264. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  72265. },
  72266. enumerable: true,
  72267. configurable: true
  72268. });
  72269. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  72270. /** Gets or sets value of right stick */
  72271. get: function () {
  72272. return this._buttonRightStick;
  72273. },
  72274. set: function (value) {
  72275. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  72276. },
  72277. enumerable: true,
  72278. configurable: true
  72279. });
  72280. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  72281. /** Gets or sets value of DPad up */
  72282. get: function () {
  72283. return this._dPadUp;
  72284. },
  72285. set: function (value) {
  72286. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  72287. },
  72288. enumerable: true,
  72289. configurable: true
  72290. });
  72291. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  72292. /** Gets or sets value of DPad down */
  72293. get: function () {
  72294. return this._dPadDown;
  72295. },
  72296. set: function (value) {
  72297. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  72298. },
  72299. enumerable: true,
  72300. configurable: true
  72301. });
  72302. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  72303. /** Gets or sets value of DPad left */
  72304. get: function () {
  72305. return this._dPadLeft;
  72306. },
  72307. set: function (value) {
  72308. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  72309. },
  72310. enumerable: true,
  72311. configurable: true
  72312. });
  72313. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  72314. /** Gets or sets value of DPad right */
  72315. get: function () {
  72316. return this._dPadRight;
  72317. },
  72318. set: function (value) {
  72319. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  72320. },
  72321. enumerable: true,
  72322. configurable: true
  72323. });
  72324. /**
  72325. * Force the gamepad to synchronize with device values
  72326. */
  72327. Xbox360Pad.prototype.update = function () {
  72328. _super.prototype.update.call(this);
  72329. if (this._isXboxOnePad) {
  72330. this.buttonA = this.browserGamepad.buttons[0].value;
  72331. this.buttonB = this.browserGamepad.buttons[1].value;
  72332. this.buttonX = this.browserGamepad.buttons[2].value;
  72333. this.buttonY = this.browserGamepad.buttons[3].value;
  72334. this.buttonLB = this.browserGamepad.buttons[4].value;
  72335. this.buttonRB = this.browserGamepad.buttons[5].value;
  72336. this.leftTrigger = this.browserGamepad.axes[2];
  72337. this.rightTrigger = this.browserGamepad.axes[5];
  72338. this.buttonBack = this.browserGamepad.buttons[9].value;
  72339. this.buttonStart = this.browserGamepad.buttons[8].value;
  72340. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  72341. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  72342. this.dPadUp = this.browserGamepad.buttons[11].value;
  72343. this.dPadDown = this.browserGamepad.buttons[12].value;
  72344. this.dPadLeft = this.browserGamepad.buttons[13].value;
  72345. this.dPadRight = this.browserGamepad.buttons[14].value;
  72346. }
  72347. else {
  72348. this.buttonA = this.browserGamepad.buttons[0].value;
  72349. this.buttonB = this.browserGamepad.buttons[1].value;
  72350. this.buttonX = this.browserGamepad.buttons[2].value;
  72351. this.buttonY = this.browserGamepad.buttons[3].value;
  72352. this.buttonLB = this.browserGamepad.buttons[4].value;
  72353. this.buttonRB = this.browserGamepad.buttons[5].value;
  72354. this.leftTrigger = this.browserGamepad.buttons[6].value;
  72355. this.rightTrigger = this.browserGamepad.buttons[7].value;
  72356. this.buttonBack = this.browserGamepad.buttons[8].value;
  72357. this.buttonStart = this.browserGamepad.buttons[9].value;
  72358. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  72359. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  72360. this.dPadUp = this.browserGamepad.buttons[12].value;
  72361. this.dPadDown = this.browserGamepad.buttons[13].value;
  72362. this.dPadLeft = this.browserGamepad.buttons[14].value;
  72363. this.dPadRight = this.browserGamepad.buttons[15].value;
  72364. }
  72365. };
  72366. Xbox360Pad.prototype.dispose = function () {
  72367. _super.prototype.dispose.call(this);
  72368. this.onButtonDownObservable.clear();
  72369. this.onButtonUpObservable.clear();
  72370. this.onPadDownObservable.clear();
  72371. this.onPadUpObservable.clear();
  72372. };
  72373. return Xbox360Pad;
  72374. }(BABYLON.Gamepad));
  72375. BABYLON.Xbox360Pad = Xbox360Pad;
  72376. })(BABYLON || (BABYLON = {}));
  72377. //# sourceMappingURL=babylon.xboxGamepad.js.map
  72378. var BABYLON;
  72379. (function (BABYLON) {
  72380. /**
  72381. * Defines the types of pose enabled controllers that are supported
  72382. */
  72383. var PoseEnabledControllerType;
  72384. (function (PoseEnabledControllerType) {
  72385. /**
  72386. * HTC Vive
  72387. */
  72388. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  72389. /**
  72390. * Oculus Rift
  72391. */
  72392. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  72393. /**
  72394. * Windows mixed reality
  72395. */
  72396. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  72397. /**
  72398. * Samsung gear VR
  72399. */
  72400. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  72401. /**
  72402. * Google Daydream
  72403. */
  72404. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  72405. /**
  72406. * Generic
  72407. */
  72408. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  72409. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  72410. /**
  72411. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72412. */
  72413. var PoseEnabledControllerHelper = /** @class */ (function () {
  72414. function PoseEnabledControllerHelper() {
  72415. }
  72416. /**
  72417. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72418. * @param vrGamepad the gamepad to initialized
  72419. * @returns a vr controller of the type the gamepad identified as
  72420. */
  72421. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  72422. // Oculus Touch
  72423. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  72424. return new BABYLON.OculusTouchController(vrGamepad);
  72425. }
  72426. // Windows Mixed Reality controllers
  72427. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  72428. return new BABYLON.WindowsMotionController(vrGamepad);
  72429. }
  72430. // HTC Vive
  72431. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  72432. return new BABYLON.ViveController(vrGamepad);
  72433. }
  72434. // Samsung/Oculus Gear VR or Oculus Go
  72435. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  72436. return new BABYLON.GearVRController(vrGamepad);
  72437. }
  72438. // Google Daydream
  72439. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  72440. return new BABYLON.DaydreamController(vrGamepad);
  72441. }
  72442. // Generic
  72443. else {
  72444. return new BABYLON.GenericController(vrGamepad);
  72445. }
  72446. };
  72447. return PoseEnabledControllerHelper;
  72448. }());
  72449. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  72450. /**
  72451. * Defines the PoseEnabledController object that contains state of a vr capable controller
  72452. */
  72453. var PoseEnabledController = /** @class */ (function (_super) {
  72454. __extends(PoseEnabledController, _super);
  72455. /**
  72456. * Creates a new PoseEnabledController from a gamepad
  72457. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  72458. */
  72459. function PoseEnabledController(browserGamepad) {
  72460. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  72461. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72462. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72463. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  72464. /**
  72465. * The device position in babylon space
  72466. */
  72467. _this.devicePosition = BABYLON.Vector3.Zero();
  72468. /**
  72469. * The device rotation in babylon space
  72470. */
  72471. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  72472. /**
  72473. * The scale factor of the device in babylon space
  72474. */
  72475. _this.deviceScaleFactor = 1;
  72476. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  72477. /**
  72478. * Internal, matrix used to convert room space to babylon space
  72479. */
  72480. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72481. /**
  72482. * Node to be used when casting a ray from the controller
  72483. */
  72484. _this._pointingPoseNode = null;
  72485. _this._workingMatrix = BABYLON.Matrix.Identity();
  72486. /**
  72487. * @hidden
  72488. */
  72489. _this._meshAttachedObservable = new BABYLON.Observable();
  72490. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  72491. _this.controllerType = PoseEnabledControllerType.GENERIC;
  72492. _this.position = BABYLON.Vector3.Zero();
  72493. _this.rotationQuaternion = new BABYLON.Quaternion();
  72494. _this._calculatedPosition = BABYLON.Vector3.Zero();
  72495. _this._calculatedRotation = new BABYLON.Quaternion();
  72496. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  72497. return _this;
  72498. }
  72499. /**
  72500. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  72501. */
  72502. PoseEnabledController.prototype.update = function () {
  72503. _super.prototype.update.call(this);
  72504. this._updatePoseAndMesh();
  72505. };
  72506. /**
  72507. * Updates only the pose device and mesh without doing any button event checking
  72508. */
  72509. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72510. var pose = this.browserGamepad.pose;
  72511. this.updateFromDevice(pose);
  72512. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72513. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72514. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72515. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72516. if (this._mesh) {
  72517. this._mesh.position.copyFrom(this.devicePosition);
  72518. if (this._mesh.rotationQuaternion) {
  72519. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72520. }
  72521. }
  72522. };
  72523. /**
  72524. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72525. * @param poseData raw pose fromthe device
  72526. */
  72527. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72528. if (poseData) {
  72529. this.rawPose = poseData;
  72530. if (poseData.position) {
  72531. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72532. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72533. this._deviceRoomPosition.z *= -1;
  72534. }
  72535. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72536. this._calculatedPosition.addInPlace(this.position);
  72537. }
  72538. var pose = this.rawPose;
  72539. if (poseData.orientation && pose.orientation) {
  72540. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72541. if (this._mesh) {
  72542. if (this._mesh.getScene().useRightHandedSystem) {
  72543. this._deviceRoomRotationQuaternion.z *= -1;
  72544. this._deviceRoomRotationQuaternion.w *= -1;
  72545. }
  72546. else {
  72547. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72548. }
  72549. }
  72550. // if the camera is set, rotate to the camera's rotation
  72551. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  72552. }
  72553. }
  72554. };
  72555. /**
  72556. * Attaches a mesh to the controller
  72557. * @param mesh the mesh to be attached
  72558. */
  72559. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  72560. if (this._mesh) {
  72561. this._mesh.parent = null;
  72562. }
  72563. this._mesh = mesh;
  72564. if (this._poseControlledCamera) {
  72565. this._mesh.parent = this._poseControlledCamera;
  72566. }
  72567. if (!this._mesh.rotationQuaternion) {
  72568. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  72569. }
  72570. // 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
  72571. this._updatePoseAndMesh();
  72572. if (this._pointingPoseNode) {
  72573. var parents = [];
  72574. var obj = this._pointingPoseNode;
  72575. while (obj.parent) {
  72576. parents.push(obj.parent);
  72577. obj = obj.parent;
  72578. }
  72579. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  72580. }
  72581. this._meshAttachedObservable.notifyObservers(mesh);
  72582. };
  72583. /**
  72584. * Attaches the controllers mesh to a camera
  72585. * @param camera the camera the mesh should be attached to
  72586. */
  72587. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  72588. this._poseControlledCamera = camera;
  72589. if (this._mesh) {
  72590. this._mesh.parent = this._poseControlledCamera;
  72591. }
  72592. };
  72593. /**
  72594. * Disposes of the controller
  72595. */
  72596. PoseEnabledController.prototype.dispose = function () {
  72597. if (this._mesh) {
  72598. this._mesh.dispose();
  72599. }
  72600. this._mesh = null;
  72601. _super.prototype.dispose.call(this);
  72602. };
  72603. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  72604. /**
  72605. * The mesh that is attached to the controller
  72606. */
  72607. get: function () {
  72608. return this._mesh;
  72609. },
  72610. enumerable: true,
  72611. configurable: true
  72612. });
  72613. /**
  72614. * Gets the ray of the controller in the direction the controller is pointing
  72615. * @param length the length the resulting ray should be
  72616. * @returns a ray in the direction the controller is pointing
  72617. */
  72618. PoseEnabledController.prototype.getForwardRay = function (length) {
  72619. if (length === void 0) { length = 100; }
  72620. if (!this.mesh) {
  72621. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  72622. }
  72623. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  72624. var origin = m.getTranslation();
  72625. var forward = new BABYLON.Vector3(0, 0, -1);
  72626. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72627. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72628. return new BABYLON.Ray(origin, direction, length);
  72629. };
  72630. /**
  72631. * Name of the child mesh that can be used to cast a ray from the controller
  72632. */
  72633. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  72634. return PoseEnabledController;
  72635. }(BABYLON.Gamepad));
  72636. BABYLON.PoseEnabledController = PoseEnabledController;
  72637. })(BABYLON || (BABYLON = {}));
  72638. //# sourceMappingURL=babylon.poseEnabledController.js.map
  72639. var BABYLON;
  72640. (function (BABYLON) {
  72641. /**
  72642. * Defines the WebVRController object that represents controllers tracked in 3D space
  72643. */
  72644. var WebVRController = /** @class */ (function (_super) {
  72645. __extends(WebVRController, _super);
  72646. /**
  72647. * Creates a new WebVRController from a gamepad
  72648. * @param vrGamepad the gamepad that the WebVRController should be created from
  72649. */
  72650. function WebVRController(vrGamepad) {
  72651. var _this = _super.call(this, vrGamepad) || this;
  72652. // Observables
  72653. /**
  72654. * Fired when the trigger state has changed
  72655. */
  72656. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  72657. /**
  72658. * Fired when the main button state has changed
  72659. */
  72660. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  72661. /**
  72662. * Fired when the secondary button state has changed
  72663. */
  72664. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72665. /**
  72666. * Fired when the pad state has changed
  72667. */
  72668. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72669. /**
  72670. * Fired when controllers stick values have changed
  72671. */
  72672. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72673. /**
  72674. * X and Y axis corrisponding to the controllers joystick
  72675. */
  72676. _this.pad = { x: 0, y: 0 };
  72677. // avoid GC, store state in a tmp object
  72678. _this._changes = {
  72679. pressChanged: false,
  72680. touchChanged: false,
  72681. valueChanged: false,
  72682. changed: false
  72683. };
  72684. _this._buttons = new Array(vrGamepad.buttons.length);
  72685. _this.hand = vrGamepad.hand;
  72686. return _this;
  72687. }
  72688. /**
  72689. * Fired when a controller button's state has changed
  72690. * @param callback the callback containing the button that was modified
  72691. */
  72692. WebVRController.prototype.onButtonStateChange = function (callback) {
  72693. this._onButtonStateChange = callback;
  72694. };
  72695. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72696. /**
  72697. * The default controller model for the controller
  72698. */
  72699. get: function () {
  72700. return this._defaultModel;
  72701. },
  72702. enumerable: true,
  72703. configurable: true
  72704. });
  72705. /**
  72706. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72707. */
  72708. WebVRController.prototype.update = function () {
  72709. _super.prototype.update.call(this);
  72710. for (var index = 0; index < this._buttons.length; index++) {
  72711. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72712. }
  72713. ;
  72714. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72715. this.pad.x = this.leftStick.x;
  72716. this.pad.y = this.leftStick.y;
  72717. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72718. }
  72719. };
  72720. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72721. if (!newState) {
  72722. newState = {
  72723. pressed: false,
  72724. touched: false,
  72725. value: 0
  72726. };
  72727. }
  72728. if (!currentState) {
  72729. this._buttons[buttonIndex] = {
  72730. pressed: newState.pressed,
  72731. touched: newState.touched,
  72732. value: newState.value
  72733. };
  72734. return;
  72735. }
  72736. this._checkChanges(newState, currentState);
  72737. if (this._changes.changed) {
  72738. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72739. this._handleButtonChange(buttonIndex, newState, this._changes);
  72740. }
  72741. this._buttons[buttonIndex].pressed = newState.pressed;
  72742. this._buttons[buttonIndex].touched = newState.touched;
  72743. // oculus triggers are never 0, thou not touched.
  72744. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72745. };
  72746. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72747. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72748. this._changes.touchChanged = newState.touched !== currentState.touched;
  72749. this._changes.valueChanged = newState.value !== currentState.value;
  72750. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72751. return this._changes;
  72752. };
  72753. /**
  72754. * Disposes of th webVRCOntroller
  72755. */
  72756. WebVRController.prototype.dispose = function () {
  72757. _super.prototype.dispose.call(this);
  72758. this.onTriggerStateChangedObservable.clear();
  72759. this.onMainButtonStateChangedObservable.clear();
  72760. this.onSecondaryButtonStateChangedObservable.clear();
  72761. this.onPadStateChangedObservable.clear();
  72762. this.onPadValuesChangedObservable.clear();
  72763. };
  72764. return WebVRController;
  72765. }(BABYLON.PoseEnabledController));
  72766. BABYLON.WebVRController = WebVRController;
  72767. })(BABYLON || (BABYLON = {}));
  72768. //# sourceMappingURL=babylon.webVRController.js.map
  72769. var BABYLON;
  72770. (function (BABYLON) {
  72771. /**
  72772. * Oculus Touch Controller
  72773. */
  72774. var OculusTouchController = /** @class */ (function (_super) {
  72775. __extends(OculusTouchController, _super);
  72776. /**
  72777. * Creates a new OculusTouchController from a gamepad
  72778. * @param vrGamepad the gamepad that the controller should be created from
  72779. */
  72780. function OculusTouchController(vrGamepad) {
  72781. var _this = _super.call(this, vrGamepad) || this;
  72782. /**
  72783. * Fired when the secondary trigger on this controller is modified
  72784. */
  72785. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72786. /**
  72787. * Fired when the thumb rest on this controller is modified
  72788. */
  72789. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72790. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72791. return _this;
  72792. }
  72793. /**
  72794. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72795. * @param scene scene in which to add meshes
  72796. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72797. */
  72798. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72799. var _this = this;
  72800. var meshName;
  72801. // Hand
  72802. if (this.hand === 'left') {
  72803. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72804. }
  72805. else { // Right is the default if no hand is specified
  72806. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72807. }
  72808. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72809. /*
  72810. Parent Mesh name: oculus_touch_left
  72811. - body
  72812. - trigger
  72813. - thumbstick
  72814. - grip
  72815. - button_y
  72816. - button_x
  72817. - button_enter
  72818. */
  72819. _this._defaultModel = newMeshes[1];
  72820. _this.attachToMesh(_this._defaultModel);
  72821. if (meshLoaded) {
  72822. meshLoaded(_this._defaultModel);
  72823. }
  72824. });
  72825. };
  72826. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72827. /**
  72828. * Fired when the A button on this controller is modified
  72829. */
  72830. get: function () {
  72831. if (this.hand === 'right') {
  72832. return this.onMainButtonStateChangedObservable;
  72833. }
  72834. else {
  72835. throw new Error('No A button on left hand');
  72836. }
  72837. },
  72838. enumerable: true,
  72839. configurable: true
  72840. });
  72841. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72842. /**
  72843. * Fired when the B button on this controller is modified
  72844. */
  72845. get: function () {
  72846. if (this.hand === 'right') {
  72847. return this.onSecondaryButtonStateChangedObservable;
  72848. }
  72849. else {
  72850. throw new Error('No B button on left hand');
  72851. }
  72852. },
  72853. enumerable: true,
  72854. configurable: true
  72855. });
  72856. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72857. /**
  72858. * Fired when the X button on this controller is modified
  72859. */
  72860. get: function () {
  72861. if (this.hand === 'left') {
  72862. return this.onMainButtonStateChangedObservable;
  72863. }
  72864. else {
  72865. throw new Error('No X button on right hand');
  72866. }
  72867. },
  72868. enumerable: true,
  72869. configurable: true
  72870. });
  72871. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72872. /**
  72873. * Fired when the Y button on this controller is modified
  72874. */
  72875. get: function () {
  72876. if (this.hand === 'left') {
  72877. return this.onSecondaryButtonStateChangedObservable;
  72878. }
  72879. else {
  72880. throw new Error('No Y button on right hand');
  72881. }
  72882. },
  72883. enumerable: true,
  72884. configurable: true
  72885. });
  72886. /**
  72887. * Called once for each button that changed state since the last frame
  72888. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72889. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72890. * 2) secondary trigger (same)
  72891. * 3) A (right) X (left), touch, pressed = value
  72892. * 4) B / Y
  72893. * 5) thumb rest
  72894. * @param buttonIdx Which button index changed
  72895. * @param state New state of the button
  72896. * @param changes Which properties on the state changed since last frame
  72897. */
  72898. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72899. var notifyObject = state; //{ state: state, changes: changes };
  72900. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72901. switch (buttonIdx) {
  72902. case 0:
  72903. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72904. return;
  72905. case 1: // index trigger
  72906. if (this._defaultModel) {
  72907. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72908. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72909. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72910. }
  72911. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72912. return;
  72913. case 2: // secondary trigger
  72914. if (this._defaultModel) {
  72915. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72916. }
  72917. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72918. return;
  72919. case 3:
  72920. if (this._defaultModel) {
  72921. if (notifyObject.pressed) {
  72922. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72923. }
  72924. else {
  72925. (this._defaultModel.getChildren()[1]).position.y = 0;
  72926. }
  72927. }
  72928. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72929. return;
  72930. case 4:
  72931. if (this._defaultModel) {
  72932. if (notifyObject.pressed) {
  72933. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72934. }
  72935. else {
  72936. (this._defaultModel.getChildren()[2]).position.y = 0;
  72937. }
  72938. }
  72939. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72940. return;
  72941. case 5:
  72942. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72943. return;
  72944. }
  72945. };
  72946. /**
  72947. * Base Url for the controller model.
  72948. */
  72949. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72950. /**
  72951. * File name for the left controller model.
  72952. */
  72953. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72954. /**
  72955. * File name for the right controller model.
  72956. */
  72957. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72958. return OculusTouchController;
  72959. }(BABYLON.WebVRController));
  72960. BABYLON.OculusTouchController = OculusTouchController;
  72961. })(BABYLON || (BABYLON = {}));
  72962. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72963. var BABYLON;
  72964. (function (BABYLON) {
  72965. /**
  72966. * Vive Controller
  72967. */
  72968. var ViveController = /** @class */ (function (_super) {
  72969. __extends(ViveController, _super);
  72970. /**
  72971. * Creates a new ViveController from a gamepad
  72972. * @param vrGamepad the gamepad that the controller should be created from
  72973. */
  72974. function ViveController(vrGamepad) {
  72975. var _this = _super.call(this, vrGamepad) || this;
  72976. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72977. _this._invertLeftStickY = true;
  72978. return _this;
  72979. }
  72980. /**
  72981. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72982. * @param scene scene in which to add meshes
  72983. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72984. */
  72985. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72986. var _this = this;
  72987. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72988. /*
  72989. Parent Mesh name: ViveWand
  72990. - body
  72991. - r_gripper
  72992. - l_gripper
  72993. - menu_button
  72994. - system_button
  72995. - trackpad
  72996. - trigger
  72997. - LED
  72998. */
  72999. _this._defaultModel = newMeshes[1];
  73000. _this.attachToMesh(_this._defaultModel);
  73001. if (meshLoaded) {
  73002. meshLoaded(_this._defaultModel);
  73003. }
  73004. });
  73005. };
  73006. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73007. /**
  73008. * Fired when the left button on this controller is modified
  73009. */
  73010. get: function () {
  73011. return this.onMainButtonStateChangedObservable;
  73012. },
  73013. enumerable: true,
  73014. configurable: true
  73015. });
  73016. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73017. /**
  73018. * Fired when the right button on this controller is modified
  73019. */
  73020. get: function () {
  73021. return this.onMainButtonStateChangedObservable;
  73022. },
  73023. enumerable: true,
  73024. configurable: true
  73025. });
  73026. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73027. /**
  73028. * Fired when the menu button on this controller is modified
  73029. */
  73030. get: function () {
  73031. return this.onSecondaryButtonStateChangedObservable;
  73032. },
  73033. enumerable: true,
  73034. configurable: true
  73035. });
  73036. /**
  73037. * Called once for each button that changed state since the last frame
  73038. * Vive mapping:
  73039. * 0: touchpad
  73040. * 1: trigger
  73041. * 2: left AND right buttons
  73042. * 3: menu button
  73043. * @param buttonIdx Which button index changed
  73044. * @param state New state of the button
  73045. * @param changes Which properties on the state changed since last frame
  73046. */
  73047. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73048. var notifyObject = state; //{ state: state, changes: changes };
  73049. switch (buttonIdx) {
  73050. case 0:
  73051. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73052. return;
  73053. case 1: // index trigger
  73054. if (this._defaultModel) {
  73055. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73056. }
  73057. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73058. return;
  73059. case 2: // left AND right button
  73060. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73061. return;
  73062. case 3:
  73063. if (this._defaultModel) {
  73064. if (notifyObject.pressed) {
  73065. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73066. }
  73067. else {
  73068. (this._defaultModel.getChildren()[2]).position.y = 0;
  73069. }
  73070. }
  73071. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73072. return;
  73073. }
  73074. };
  73075. /**
  73076. * Base Url for the controller model.
  73077. */
  73078. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73079. /**
  73080. * File name for the controller model.
  73081. */
  73082. ViveController.MODEL_FILENAME = 'wand.babylon';
  73083. return ViveController;
  73084. }(BABYLON.WebVRController));
  73085. BABYLON.ViveController = ViveController;
  73086. })(BABYLON || (BABYLON = {}));
  73087. //# sourceMappingURL=babylon.viveController.js.map
  73088. var BABYLON;
  73089. (function (BABYLON) {
  73090. /**
  73091. * Generic Controller
  73092. */
  73093. var GenericController = /** @class */ (function (_super) {
  73094. __extends(GenericController, _super);
  73095. /**
  73096. * Creates a new GenericController from a gamepad
  73097. * @param vrGamepad the gamepad that the controller should be created from
  73098. */
  73099. function GenericController(vrGamepad) {
  73100. return _super.call(this, vrGamepad) || this;
  73101. }
  73102. /**
  73103. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73104. * @param scene scene in which to add meshes
  73105. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73106. */
  73107. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73108. var _this = this;
  73109. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  73110. _this._defaultModel = newMeshes[1];
  73111. _this.attachToMesh(_this._defaultModel);
  73112. if (meshLoaded) {
  73113. meshLoaded(_this._defaultModel);
  73114. }
  73115. });
  73116. };
  73117. /**
  73118. * Called once for each button that changed state since the last frame
  73119. * @param buttonIdx Which button index changed
  73120. * @param state New state of the button
  73121. * @param changes Which properties on the state changed since last frame
  73122. */
  73123. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73124. console.log("Button id: " + buttonIdx + "state: ");
  73125. console.dir(state);
  73126. };
  73127. /**
  73128. * Base Url for the controller model.
  73129. */
  73130. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73131. /**
  73132. * File name for the controller model.
  73133. */
  73134. GenericController.MODEL_FILENAME = 'generic.babylon';
  73135. return GenericController;
  73136. }(BABYLON.WebVRController));
  73137. BABYLON.GenericController = GenericController;
  73138. })(BABYLON || (BABYLON = {}));
  73139. //# sourceMappingURL=babylon.genericController.js.map
  73140. var BABYLON;
  73141. (function (BABYLON) {
  73142. /**
  73143. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  73144. */
  73145. var LoadedMeshInfo = /** @class */ (function () {
  73146. function LoadedMeshInfo() {
  73147. /**
  73148. * Map of the button meshes contained in the controller
  73149. */
  73150. this.buttonMeshes = {};
  73151. /**
  73152. * Map of the axis meshes contained in the controller
  73153. */
  73154. this.axisMeshes = {};
  73155. }
  73156. return LoadedMeshInfo;
  73157. }());
  73158. /**
  73159. * Defines the WindowsMotionController object that the state of the windows motion controller
  73160. */
  73161. var WindowsMotionController = /** @class */ (function (_super) {
  73162. __extends(WindowsMotionController, _super);
  73163. /**
  73164. * Creates a new WindowsMotionController from a gamepad
  73165. * @param vrGamepad the gamepad that the controller should be created from
  73166. */
  73167. function WindowsMotionController(vrGamepad) {
  73168. var _this = _super.call(this, vrGamepad) || this;
  73169. _this._mapping = {
  73170. // Semantic button names
  73171. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  73172. // A mapping of the button name to glTF model node name
  73173. // that should be transformed by button value.
  73174. buttonMeshNames: {
  73175. 'trigger': 'SELECT',
  73176. 'menu': 'MENU',
  73177. 'grip': 'GRASP',
  73178. 'thumbstick': 'THUMBSTICK_PRESS',
  73179. 'trackpad': 'TOUCHPAD_PRESS'
  73180. },
  73181. // This mapping is used to translate from the Motion Controller to Babylon semantics
  73182. buttonObservableNames: {
  73183. 'trigger': 'onTriggerStateChangedObservable',
  73184. 'menu': 'onSecondaryButtonStateChangedObservable',
  73185. 'grip': 'onMainButtonStateChangedObservable',
  73186. 'thumbstick': 'onPadStateChangedObservable',
  73187. 'trackpad': 'onTrackpadChangedObservable'
  73188. },
  73189. // A mapping of the axis name to glTF model node name
  73190. // that should be transformed by axis value.
  73191. // This array mirrors the browserGamepad.axes array, such that
  73192. // the mesh corresponding to axis 0 is in this array index 0.
  73193. axisMeshNames: [
  73194. 'THUMBSTICK_X',
  73195. 'THUMBSTICK_Y',
  73196. 'TOUCHPAD_TOUCH_X',
  73197. 'TOUCHPAD_TOUCH_Y'
  73198. ],
  73199. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  73200. };
  73201. /**
  73202. * Fired when the trackpad on this controller is clicked
  73203. */
  73204. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  73205. /**
  73206. * Fired when the trackpad on this controller is modified
  73207. */
  73208. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  73209. /**
  73210. * The current x and y values of this controller's trackpad
  73211. */
  73212. _this.trackpad = { x: 0, y: 0 };
  73213. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  73214. _this._loadedMeshInfo = null;
  73215. return _this;
  73216. }
  73217. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  73218. /**
  73219. * Fired when the trigger on this controller is modified
  73220. */
  73221. get: function () {
  73222. return this.onTriggerStateChangedObservable;
  73223. },
  73224. enumerable: true,
  73225. configurable: true
  73226. });
  73227. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  73228. /**
  73229. * Fired when the menu button on this controller is modified
  73230. */
  73231. get: function () {
  73232. return this.onSecondaryButtonStateChangedObservable;
  73233. },
  73234. enumerable: true,
  73235. configurable: true
  73236. });
  73237. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  73238. /**
  73239. * Fired when the grip button on this controller is modified
  73240. */
  73241. get: function () {
  73242. return this.onMainButtonStateChangedObservable;
  73243. },
  73244. enumerable: true,
  73245. configurable: true
  73246. });
  73247. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  73248. /**
  73249. * Fired when the thumbstick button on this controller is modified
  73250. */
  73251. get: function () {
  73252. return this.onPadStateChangedObservable;
  73253. },
  73254. enumerable: true,
  73255. configurable: true
  73256. });
  73257. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  73258. /**
  73259. * Fired when the touchpad button on this controller is modified
  73260. */
  73261. get: function () {
  73262. return this.onTrackpadChangedObservable;
  73263. },
  73264. enumerable: true,
  73265. configurable: true
  73266. });
  73267. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  73268. /**
  73269. * Fired when the touchpad values on this controller are modified
  73270. */
  73271. get: function () {
  73272. return this.onTrackpadValuesChangedObservable;
  73273. },
  73274. enumerable: true,
  73275. configurable: true
  73276. });
  73277. WindowsMotionController.prototype._updateTrackpad = function () {
  73278. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  73279. this.trackpad.x = this.browserGamepad["axes"][2];
  73280. this.trackpad.y = this.browserGamepad["axes"][3];
  73281. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  73282. }
  73283. };
  73284. /**
  73285. * Called once per frame by the engine.
  73286. */
  73287. WindowsMotionController.prototype.update = function () {
  73288. _super.prototype.update.call(this);
  73289. if (this.browserGamepad.axes) {
  73290. this._updateTrackpad();
  73291. // Only need to animate axes if there is a loaded mesh
  73292. if (this._loadedMeshInfo) {
  73293. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  73294. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  73295. }
  73296. }
  73297. }
  73298. };
  73299. /**
  73300. * Called once for each button that changed state since the last frame
  73301. * @param buttonIdx Which button index changed
  73302. * @param state New state of the button
  73303. * @param changes Which properties on the state changed since last frame
  73304. */
  73305. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73306. var buttonName = this._mapping.buttons[buttonIdx];
  73307. if (!buttonName) {
  73308. return;
  73309. }
  73310. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  73311. this._updateTrackpad();
  73312. // Only emit events for buttons that we know how to map from index to name
  73313. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  73314. if (observable) {
  73315. observable.notifyObservers(state);
  73316. }
  73317. this._lerpButtonTransform(buttonName, state.value);
  73318. };
  73319. /**
  73320. * Moves the buttons on the controller mesh based on their current state
  73321. * @param buttonName the name of the button to move
  73322. * @param buttonValue the value of the button which determines the buttons new position
  73323. */
  73324. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  73325. // If there is no loaded mesh, there is nothing to transform.
  73326. if (!this._loadedMeshInfo) {
  73327. return;
  73328. }
  73329. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  73330. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73331. return;
  73332. }
  73333. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  73334. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  73335. };
  73336. /**
  73337. * Moves the axis on the controller mesh based on its current state
  73338. * @param axis the index of the axis
  73339. * @param axisValue the value of the axis which determines the meshes new position
  73340. * @hidden
  73341. */
  73342. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  73343. if (!this._loadedMeshInfo) {
  73344. return;
  73345. }
  73346. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  73347. if (!meshInfo) {
  73348. return;
  73349. }
  73350. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73351. return;
  73352. }
  73353. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  73354. var lerpValue = axisValue * 0.5 + 0.5;
  73355. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  73356. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  73357. };
  73358. /**
  73359. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73360. * @param scene scene in which to add meshes
  73361. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73362. */
  73363. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  73364. var _this = this;
  73365. if (forceDefault === void 0) { forceDefault = false; }
  73366. var path;
  73367. var filename;
  73368. // Checking if GLB loader is present
  73369. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  73370. // Determine the device specific folder based on the ID suffix
  73371. var device = 'default';
  73372. if (this.id && !forceDefault) {
  73373. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  73374. device = ((match && match[0]) || device);
  73375. }
  73376. // Hand
  73377. if (this.hand === 'left') {
  73378. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  73379. }
  73380. else { // Right is the default if no hand is specified
  73381. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  73382. }
  73383. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  73384. }
  73385. else {
  73386. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  73387. path = BABYLON.GenericController.MODEL_BASE_URL;
  73388. filename = BABYLON.GenericController.MODEL_FILENAME;
  73389. }
  73390. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  73391. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  73392. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  73393. if (!_this._loadedMeshInfo) {
  73394. return;
  73395. }
  73396. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  73397. _this.attachToMesh(_this._defaultModel);
  73398. if (meshLoaded) {
  73399. meshLoaded(_this._defaultModel);
  73400. }
  73401. }, null, function (scene, message) {
  73402. BABYLON.Tools.Log(message);
  73403. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  73404. if (!forceDefault) {
  73405. _this.initControllerMesh(scene, meshLoaded, true);
  73406. }
  73407. });
  73408. };
  73409. /**
  73410. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  73411. * can be transformed by button presses and axes values, based on this._mapping.
  73412. *
  73413. * @param scene scene in which the meshes exist
  73414. * @param meshes list of meshes that make up the controller model to process
  73415. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  73416. */
  73417. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  73418. var loadedMeshInfo = null;
  73419. // Create a new mesh to contain the glTF hierarchy
  73420. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  73421. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  73422. var childMesh = null;
  73423. for (var i = 0; i < meshes.length; i++) {
  73424. var mesh = meshes[i];
  73425. if (!mesh.parent) {
  73426. // Exclude controller meshes from picking results
  73427. mesh.isPickable = false;
  73428. // Handle root node, attach to the new parentMesh
  73429. childMesh = mesh;
  73430. break;
  73431. }
  73432. }
  73433. if (childMesh) {
  73434. childMesh.setParent(parentMesh);
  73435. // Create our mesh info. Note that this method will always return non-null.
  73436. loadedMeshInfo = this.createMeshInfo(parentMesh);
  73437. }
  73438. else {
  73439. BABYLON.Tools.Warn('Could not find root node in model file.');
  73440. }
  73441. return loadedMeshInfo;
  73442. };
  73443. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  73444. var loadedMeshInfo = new LoadedMeshInfo();
  73445. var i;
  73446. loadedMeshInfo.rootNode = rootNode;
  73447. // Reset the caches
  73448. loadedMeshInfo.buttonMeshes = {};
  73449. loadedMeshInfo.axisMeshes = {};
  73450. // Button Meshes
  73451. for (i = 0; i < this._mapping.buttons.length; i++) {
  73452. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  73453. if (!buttonMeshName) {
  73454. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  73455. continue;
  73456. }
  73457. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  73458. if (!buttonMesh) {
  73459. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  73460. continue;
  73461. }
  73462. var buttonMeshInfo = {
  73463. index: i,
  73464. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  73465. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  73466. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  73467. };
  73468. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  73469. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  73470. }
  73471. else {
  73472. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  73473. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  73474. '(VALUE: ' + !!buttonMeshInfo.value +
  73475. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  73476. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  73477. ')');
  73478. }
  73479. }
  73480. // Axis Meshes
  73481. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  73482. var axisMeshName = this._mapping.axisMeshNames[i];
  73483. if (!axisMeshName) {
  73484. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  73485. continue;
  73486. }
  73487. var axisMesh = getChildByName(rootNode, axisMeshName);
  73488. if (!axisMesh) {
  73489. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  73490. continue;
  73491. }
  73492. var axisMeshInfo = {
  73493. index: i,
  73494. value: getImmediateChildByName(axisMesh, 'VALUE'),
  73495. min: getImmediateChildByName(axisMesh, 'MIN'),
  73496. max: getImmediateChildByName(axisMesh, 'MAX')
  73497. };
  73498. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  73499. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  73500. }
  73501. else {
  73502. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  73503. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  73504. '(VALUE: ' + !!axisMeshInfo.value +
  73505. ', MIN: ' + !!axisMeshInfo.min +
  73506. ', MAX:' + !!axisMeshInfo.max +
  73507. ')');
  73508. }
  73509. }
  73510. // Pointing Ray
  73511. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73512. if (!loadedMeshInfo.pointingPoseNode) {
  73513. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73514. }
  73515. else {
  73516. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73517. }
  73518. return loadedMeshInfo;
  73519. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73520. function getChildByName(node, name) {
  73521. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73522. }
  73523. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73524. function getImmediateChildByName(node, name) {
  73525. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73526. }
  73527. };
  73528. /**
  73529. * Gets the ray of the controller in the direction the controller is pointing
  73530. * @param length the length the resulting ray should be
  73531. * @returns a ray in the direction the controller is pointing
  73532. */
  73533. WindowsMotionController.prototype.getForwardRay = function (length) {
  73534. if (length === void 0) { length = 100; }
  73535. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73536. return _super.prototype.getForwardRay.call(this, length);
  73537. }
  73538. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73539. var origin = m.getTranslation();
  73540. var forward = new BABYLON.Vector3(0, 0, -1);
  73541. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73542. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73543. return new BABYLON.Ray(origin, direction, length);
  73544. };
  73545. /**
  73546. * Disposes of the controller
  73547. */
  73548. WindowsMotionController.prototype.dispose = function () {
  73549. _super.prototype.dispose.call(this);
  73550. this.onTrackpadChangedObservable.clear();
  73551. };
  73552. /**
  73553. * The base url used to load the left and right controller models
  73554. */
  73555. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  73556. /**
  73557. * The name of the left controller model file
  73558. */
  73559. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  73560. /**
  73561. * The name of the right controller model file
  73562. */
  73563. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  73564. /**
  73565. * The controller name prefix for this controller type
  73566. */
  73567. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  73568. /**
  73569. * The controller id pattern for this controller type
  73570. */
  73571. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  73572. return WindowsMotionController;
  73573. }(BABYLON.WebVRController));
  73574. BABYLON.WindowsMotionController = WindowsMotionController;
  73575. })(BABYLON || (BABYLON = {}));
  73576. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73577. var BABYLON;
  73578. (function (BABYLON) {
  73579. /**
  73580. * Gear VR Controller
  73581. */
  73582. var GearVRController = /** @class */ (function (_super) {
  73583. __extends(GearVRController, _super);
  73584. /**
  73585. * Creates a new GearVRController from a gamepad
  73586. * @param vrGamepad the gamepad that the controller should be created from
  73587. */
  73588. function GearVRController(vrGamepad) {
  73589. var _this = _super.call(this, vrGamepad) || this;
  73590. _this._maxRotationDistFromHeadset = Math.PI / 5;
  73591. _this._draggedRoomRotation = 0;
  73592. _this._tmpVector = new BABYLON.Vector3();
  73593. _this._buttonIndexToObservableNameMap = [
  73594. 'onTrackpadChangedObservable',
  73595. 'onTriggerStateChangedObservable' // Trigger
  73596. ];
  73597. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  73598. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  73599. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  73600. return _this;
  73601. }
  73602. /**
  73603. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  73604. * @param poseData raw pose fromthe device
  73605. */
  73606. GearVRController.prototype.updateFromDevice = function (poseData) {
  73607. _super.prototype.updateFromDevice.call(this, poseData);
  73608. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  73609. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  73610. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  73611. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  73612. // Find the radian distance away that the headset is from the controllers rotation
  73613. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  73614. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  73615. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  73616. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  73617. this._draggedRoomRotation += rotationAmount;
  73618. // Rotate controller around headset
  73619. var sin = Math.sin(-rotationAmount);
  73620. var cos = Math.cos(-rotationAmount);
  73621. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  73622. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  73623. }
  73624. }
  73625. }
  73626. };
  73627. /**
  73628. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73629. * @param scene scene in which to add meshes
  73630. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73631. */
  73632. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73633. var _this = this;
  73634. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  73635. // Offset the controller so it will rotate around the users wrist
  73636. var mesh = new BABYLON.Mesh("", scene);
  73637. newMeshes[1].parent = mesh;
  73638. newMeshes[1].position.z = -0.15;
  73639. _this._defaultModel = mesh;
  73640. _this.attachToMesh(_this._defaultModel);
  73641. if (meshLoaded) {
  73642. meshLoaded(_this._defaultModel);
  73643. }
  73644. });
  73645. };
  73646. /**
  73647. * Called once for each button that changed state since the last frame
  73648. * @param buttonIdx Which button index changed
  73649. * @param state New state of the button
  73650. * @param changes Which properties on the state changed since last frame
  73651. */
  73652. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73653. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  73654. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  73655. // Only emit events for buttons that we know how to map from index to observable
  73656. var observable = this[observableName];
  73657. if (observable) {
  73658. observable.notifyObservers(state);
  73659. }
  73660. }
  73661. };
  73662. /**
  73663. * Base Url for the controller model.
  73664. */
  73665. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73666. /**
  73667. * File name for the controller model.
  73668. */
  73669. GearVRController.MODEL_FILENAME = 'generic.babylon';
  73670. /**
  73671. * Gamepad Id prefix used to identify this controller.
  73672. */
  73673. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  73674. return GearVRController;
  73675. }(BABYLON.WebVRController));
  73676. BABYLON.GearVRController = GearVRController;
  73677. })(BABYLON || (BABYLON = {}));
  73678. //# sourceMappingURL=babylon.gearVRController.js.map
  73679. var BABYLON;
  73680. (function (BABYLON) {
  73681. /**
  73682. * Google Daydream controller
  73683. */
  73684. var DaydreamController = /** @class */ (function (_super) {
  73685. __extends(DaydreamController, _super);
  73686. /**
  73687. * Creates a new DaydreamController from a gamepad
  73688. * @param vrGamepad the gamepad that the controller should be created from
  73689. */
  73690. function DaydreamController(vrGamepad) {
  73691. var _this = _super.call(this, vrGamepad) || this;
  73692. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  73693. return _this;
  73694. }
  73695. /**
  73696. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73697. * @param scene scene in which to add meshes
  73698. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73699. */
  73700. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73701. var _this = this;
  73702. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73703. _this._defaultModel = newMeshes[1];
  73704. _this.attachToMesh(_this._defaultModel);
  73705. if (meshLoaded) {
  73706. meshLoaded(_this._defaultModel);
  73707. }
  73708. });
  73709. };
  73710. /**
  73711. * Called once for each button that changed state since the last frame
  73712. * @param buttonIdx Which button index changed
  73713. * @param state New state of the button
  73714. * @param changes Which properties on the state changed since last frame
  73715. */
  73716. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73717. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73718. if (buttonIdx === 0) {
  73719. var observable = this.onTriggerStateChangedObservable;
  73720. if (observable) {
  73721. observable.notifyObservers(state);
  73722. }
  73723. }
  73724. else {
  73725. // If the app or home buttons are ever made available
  73726. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73727. }
  73728. };
  73729. /**
  73730. * Base Url for the controller model.
  73731. */
  73732. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73733. /**
  73734. * File name for the controller model.
  73735. */
  73736. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73737. /**
  73738. * Gamepad Id prefix used to identify Daydream Controller.
  73739. */
  73740. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73741. return DaydreamController;
  73742. }(BABYLON.WebVRController));
  73743. BABYLON.DaydreamController = DaydreamController;
  73744. })(BABYLON || (BABYLON = {}));
  73745. //# sourceMappingURL=babylon.daydreamController.js.map
  73746. var BABYLON;
  73747. (function (BABYLON) {
  73748. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  73749. get: function () {
  73750. if (!this._gamepadManager) {
  73751. this._gamepadManager = new BABYLON.GamepadManager(this);
  73752. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  73753. if (!component) {
  73754. component = new GamepadSystemSceneComponent(this);
  73755. this._addComponent(component);
  73756. }
  73757. }
  73758. return this._gamepadManager;
  73759. },
  73760. enumerable: true,
  73761. configurable: true
  73762. });
  73763. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  73764. this.add(new BABYLON.FreeCameraGamepadInput());
  73765. return this;
  73766. };
  73767. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  73768. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  73769. return this;
  73770. };
  73771. /**
  73772. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  73773. */
  73774. var GamepadSystemSceneComponent = /** @class */ (function () {
  73775. /**
  73776. * Creates a new instance of the component for the given scene
  73777. * @param scene Defines the scene to register the component in
  73778. */
  73779. function GamepadSystemSceneComponent(scene) {
  73780. /**
  73781. * The component name helpfull to identify the component in the list of scene components.
  73782. */
  73783. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  73784. this.scene = scene;
  73785. }
  73786. /**
  73787. * Registers the component in a given scene
  73788. */
  73789. GamepadSystemSceneComponent.prototype.register = function () {
  73790. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  73791. };
  73792. /**
  73793. * Rebuilds the elements related to this component in case of
  73794. * context lost for instance.
  73795. */
  73796. GamepadSystemSceneComponent.prototype.rebuild = function () {
  73797. // Nothing to do for gamepads
  73798. };
  73799. /**
  73800. * Disposes the component and the associated ressources
  73801. */
  73802. GamepadSystemSceneComponent.prototype.dispose = function () {
  73803. var gamepadManager = this.scene._gamepadManager;
  73804. if (gamepadManager) {
  73805. gamepadManager.dispose();
  73806. this.scene._gamepadManager = null;
  73807. }
  73808. };
  73809. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  73810. var gamepadManager = this.scene._gamepadManager;
  73811. if (gamepadManager && gamepadManager._isMonitoring) {
  73812. gamepadManager._checkGamepadsStatus();
  73813. }
  73814. };
  73815. return GamepadSystemSceneComponent;
  73816. }());
  73817. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  73818. })(BABYLON || (BABYLON = {}));
  73819. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  73820. var BABYLON;
  73821. (function (BABYLON) {
  73822. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  73823. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  73824. });
  73825. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  73826. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  73827. });
  73828. var FollowCamera = /** @class */ (function (_super) {
  73829. __extends(FollowCamera, _super);
  73830. function FollowCamera(name, position, scene, lockedTarget) {
  73831. if (lockedTarget === void 0) { lockedTarget = null; }
  73832. var _this = _super.call(this, name, position, scene) || this;
  73833. _this.radius = 12;
  73834. _this.rotationOffset = 0;
  73835. _this.heightOffset = 4;
  73836. _this.cameraAcceleration = 0.05;
  73837. _this.maxCameraSpeed = 20;
  73838. _this.lockedTarget = lockedTarget;
  73839. return _this;
  73840. }
  73841. FollowCamera.prototype.getRadians = function (degrees) {
  73842. return degrees * Math.PI / 180;
  73843. };
  73844. FollowCamera.prototype.follow = function (cameraTarget) {
  73845. if (!cameraTarget)
  73846. return;
  73847. var yRotation;
  73848. if (cameraTarget.rotationQuaternion) {
  73849. var rotMatrix = new BABYLON.Matrix();
  73850. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73851. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73852. }
  73853. else {
  73854. yRotation = cameraTarget.rotation.y;
  73855. }
  73856. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73857. var targetPosition = cameraTarget.getAbsolutePosition();
  73858. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73859. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73860. var dx = targetX - this.position.x;
  73861. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73862. var dz = (targetZ) - this.position.z;
  73863. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73864. var vy = dy * this.cameraAcceleration;
  73865. var vz = dz * this.cameraAcceleration * 2;
  73866. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73867. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73868. }
  73869. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73870. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73871. }
  73872. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73873. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73874. }
  73875. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73876. this.setTarget(targetPosition);
  73877. };
  73878. FollowCamera.prototype._checkInputs = function () {
  73879. _super.prototype._checkInputs.call(this);
  73880. if (this.lockedTarget) {
  73881. this.follow(this.lockedTarget);
  73882. }
  73883. };
  73884. FollowCamera.prototype.getClassName = function () {
  73885. return "FollowCamera";
  73886. };
  73887. __decorate([
  73888. BABYLON.serialize()
  73889. ], FollowCamera.prototype, "radius", void 0);
  73890. __decorate([
  73891. BABYLON.serialize()
  73892. ], FollowCamera.prototype, "rotationOffset", void 0);
  73893. __decorate([
  73894. BABYLON.serialize()
  73895. ], FollowCamera.prototype, "heightOffset", void 0);
  73896. __decorate([
  73897. BABYLON.serialize()
  73898. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73899. __decorate([
  73900. BABYLON.serialize()
  73901. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73902. __decorate([
  73903. BABYLON.serializeAsMeshReference("lockedTargetId")
  73904. ], FollowCamera.prototype, "lockedTarget", void 0);
  73905. return FollowCamera;
  73906. }(BABYLON.TargetCamera));
  73907. BABYLON.FollowCamera = FollowCamera;
  73908. var ArcFollowCamera = /** @class */ (function (_super) {
  73909. __extends(ArcFollowCamera, _super);
  73910. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73911. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73912. _this.alpha = alpha;
  73913. _this.beta = beta;
  73914. _this.radius = radius;
  73915. _this.target = target;
  73916. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73917. _this.follow();
  73918. return _this;
  73919. }
  73920. ArcFollowCamera.prototype.follow = function () {
  73921. if (!this.target) {
  73922. return;
  73923. }
  73924. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73925. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73926. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73927. var targetPosition = this.target.getAbsolutePosition();
  73928. this.position = targetPosition.add(this._cartesianCoordinates);
  73929. this.setTarget(targetPosition);
  73930. };
  73931. ArcFollowCamera.prototype._checkInputs = function () {
  73932. _super.prototype._checkInputs.call(this);
  73933. this.follow();
  73934. };
  73935. ArcFollowCamera.prototype.getClassName = function () {
  73936. return "ArcFollowCamera";
  73937. };
  73938. return ArcFollowCamera;
  73939. }(BABYLON.TargetCamera));
  73940. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73941. })(BABYLON || (BABYLON = {}));
  73942. //# sourceMappingURL=babylon.followCamera.js.map
  73943. var BABYLON;
  73944. (function (BABYLON) {
  73945. // We're mainly based on the logic defined into the FreeCamera code
  73946. var UniversalCamera = /** @class */ (function (_super) {
  73947. __extends(UniversalCamera, _super);
  73948. //-- end properties for backward compatibility for inputs
  73949. function UniversalCamera(name, position, scene) {
  73950. var _this = _super.call(this, name, position, scene) || this;
  73951. _this.inputs.addGamepad();
  73952. return _this;
  73953. }
  73954. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73955. //-- Begin properties for backward compatibility for inputs
  73956. get: function () {
  73957. var gamepad = this.inputs.attached["gamepad"];
  73958. if (gamepad)
  73959. return gamepad.gamepadAngularSensibility;
  73960. return 0;
  73961. },
  73962. set: function (value) {
  73963. var gamepad = this.inputs.attached["gamepad"];
  73964. if (gamepad)
  73965. gamepad.gamepadAngularSensibility = value;
  73966. },
  73967. enumerable: true,
  73968. configurable: true
  73969. });
  73970. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73971. get: function () {
  73972. var gamepad = this.inputs.attached["gamepad"];
  73973. if (gamepad)
  73974. return gamepad.gamepadMoveSensibility;
  73975. return 0;
  73976. },
  73977. set: function (value) {
  73978. var gamepad = this.inputs.attached["gamepad"];
  73979. if (gamepad)
  73980. gamepad.gamepadMoveSensibility = value;
  73981. },
  73982. enumerable: true,
  73983. configurable: true
  73984. });
  73985. UniversalCamera.prototype.getClassName = function () {
  73986. return "UniversalCamera";
  73987. };
  73988. return UniversalCamera;
  73989. }(BABYLON.TouchCamera));
  73990. BABYLON.UniversalCamera = UniversalCamera;
  73991. })(BABYLON || (BABYLON = {}));
  73992. //# sourceMappingURL=babylon.universalCamera.js.map
  73993. var BABYLON;
  73994. (function (BABYLON) {
  73995. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  73996. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  73997. });
  73998. // We're mainly based on the logic defined into the FreeCamera code
  73999. var GamepadCamera = /** @class */ (function (_super) {
  74000. __extends(GamepadCamera, _super);
  74001. //-- end properties for backward compatibility for inputs
  74002. function GamepadCamera(name, position, scene) {
  74003. return _super.call(this, name, position, scene) || this;
  74004. }
  74005. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74006. //-- Begin properties for backward compatibility for inputs
  74007. get: function () {
  74008. var gamepad = this.inputs.attached["gamepad"];
  74009. if (gamepad)
  74010. return gamepad.gamepadAngularSensibility;
  74011. return 0;
  74012. },
  74013. set: function (value) {
  74014. var gamepad = this.inputs.attached["gamepad"];
  74015. if (gamepad)
  74016. gamepad.gamepadAngularSensibility = value;
  74017. },
  74018. enumerable: true,
  74019. configurable: true
  74020. });
  74021. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74022. get: function () {
  74023. var gamepad = this.inputs.attached["gamepad"];
  74024. if (gamepad)
  74025. return gamepad.gamepadMoveSensibility;
  74026. return 0;
  74027. },
  74028. set: function (value) {
  74029. var gamepad = this.inputs.attached["gamepad"];
  74030. if (gamepad)
  74031. gamepad.gamepadMoveSensibility = value;
  74032. },
  74033. enumerable: true,
  74034. configurable: true
  74035. });
  74036. GamepadCamera.prototype.getClassName = function () {
  74037. return "GamepadCamera";
  74038. };
  74039. return GamepadCamera;
  74040. }(BABYLON.UniversalCamera));
  74041. BABYLON.GamepadCamera = GamepadCamera;
  74042. })(BABYLON || (BABYLON = {}));
  74043. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74044. var BABYLON;
  74045. (function (BABYLON) {
  74046. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74047. function PostProcessRenderPipelineManager() {
  74048. this._renderPipelines = {};
  74049. }
  74050. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74051. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74052. };
  74053. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74054. if (unique === void 0) { unique = false; }
  74055. var renderPipeline = this._renderPipelines[renderPipelineName];
  74056. if (!renderPipeline) {
  74057. return;
  74058. }
  74059. renderPipeline._attachCameras(cameras, unique);
  74060. };
  74061. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74062. var renderPipeline = this._renderPipelines[renderPipelineName];
  74063. if (!renderPipeline) {
  74064. return;
  74065. }
  74066. renderPipeline._detachCameras(cameras);
  74067. };
  74068. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74069. var renderPipeline = this._renderPipelines[renderPipelineName];
  74070. if (!renderPipeline) {
  74071. return;
  74072. }
  74073. renderPipeline._enableEffect(renderEffectName, cameras);
  74074. };
  74075. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74076. var renderPipeline = this._renderPipelines[renderPipelineName];
  74077. if (!renderPipeline) {
  74078. return;
  74079. }
  74080. renderPipeline._disableEffect(renderEffectName, cameras);
  74081. };
  74082. PostProcessRenderPipelineManager.prototype.update = function () {
  74083. for (var renderPipelineName in this._renderPipelines) {
  74084. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74085. var pipeline = this._renderPipelines[renderPipelineName];
  74086. if (!pipeline.isSupported) {
  74087. pipeline.dispose();
  74088. delete this._renderPipelines[renderPipelineName];
  74089. }
  74090. else {
  74091. pipeline._update();
  74092. }
  74093. }
  74094. }
  74095. };
  74096. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  74097. for (var renderPipelineName in this._renderPipelines) {
  74098. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74099. var pipeline = this._renderPipelines[renderPipelineName];
  74100. pipeline._rebuild();
  74101. }
  74102. }
  74103. };
  74104. PostProcessRenderPipelineManager.prototype.dispose = function () {
  74105. for (var renderPipelineName in this._renderPipelines) {
  74106. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74107. var pipeline = this._renderPipelines[renderPipelineName];
  74108. pipeline.dispose();
  74109. }
  74110. }
  74111. };
  74112. return PostProcessRenderPipelineManager;
  74113. }());
  74114. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  74115. })(BABYLON || (BABYLON = {}));
  74116. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  74117. var BABYLON;
  74118. (function (BABYLON) {
  74119. /**
  74120. * This represents a set of one or more post processes in Babylon.
  74121. * A post process can be used to apply a shader to a texture after it is rendered.
  74122. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  74123. */
  74124. var PostProcessRenderEffect = /** @class */ (function () {
  74125. /**
  74126. * Instantiates a post process render effect.
  74127. * A post process can be used to apply a shader to a texture after it is rendered.
  74128. * @param engine The engine the effect is tied to
  74129. * @param name The name of the effect
  74130. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  74131. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  74132. */
  74133. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  74134. this._name = name;
  74135. this._singleInstance = singleInstance || true;
  74136. this._getPostProcesses = getPostProcesses;
  74137. this._cameras = {};
  74138. this._indicesForCamera = {};
  74139. this._postProcesses = {};
  74140. }
  74141. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  74142. /**
  74143. * Checks if all the post processes in the effect are supported.
  74144. */
  74145. get: function () {
  74146. for (var index in this._postProcesses) {
  74147. if (this._postProcesses.hasOwnProperty(index)) {
  74148. var pps = this._postProcesses[index];
  74149. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  74150. if (!pps[ppIndex].isSupported) {
  74151. return false;
  74152. }
  74153. }
  74154. }
  74155. }
  74156. return true;
  74157. },
  74158. enumerable: true,
  74159. configurable: true
  74160. });
  74161. /**
  74162. * Updates the current state of the effect
  74163. */
  74164. PostProcessRenderEffect.prototype._update = function () {
  74165. };
  74166. /**
  74167. * Attaches the effect on cameras
  74168. * @param cameras The camera to attach to.
  74169. */
  74170. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  74171. var _this = this;
  74172. var cameraKey;
  74173. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74174. if (!cams) {
  74175. return;
  74176. }
  74177. for (var i = 0; i < cams.length; i++) {
  74178. var camera = cams[i];
  74179. var cameraName = camera.name;
  74180. if (this._singleInstance) {
  74181. cameraKey = 0;
  74182. }
  74183. else {
  74184. cameraKey = cameraName;
  74185. }
  74186. if (!this._postProcesses[cameraKey]) {
  74187. var postProcess = this._getPostProcesses();
  74188. if (postProcess) {
  74189. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  74190. }
  74191. }
  74192. if (!this._indicesForCamera[cameraName]) {
  74193. this._indicesForCamera[cameraName] = [];
  74194. }
  74195. this._postProcesses[cameraKey].forEach(function (postProcess) {
  74196. var index = camera.attachPostProcess(postProcess);
  74197. _this._indicesForCamera[cameraName].push(index);
  74198. });
  74199. if (!this._cameras[cameraName]) {
  74200. this._cameras[cameraName] = camera;
  74201. }
  74202. }
  74203. };
  74204. /**
  74205. * Detatches the effect on cameras
  74206. * @param cameras The camera to detatch from.
  74207. */
  74208. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  74209. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74210. if (!cams) {
  74211. return;
  74212. }
  74213. for (var i = 0; i < cams.length; i++) {
  74214. var camera = cams[i];
  74215. var cameraName = camera.name;
  74216. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74217. camera.detachPostProcess(postProcess);
  74218. });
  74219. if (this._cameras[cameraName]) {
  74220. //this._indicesForCamera.splice(index, 1);
  74221. this._cameras[cameraName] = null;
  74222. }
  74223. }
  74224. };
  74225. /**
  74226. * Enables the effect on given cameras
  74227. * @param cameras The camera to enable.
  74228. */
  74229. PostProcessRenderEffect.prototype._enable = function (cameras) {
  74230. var _this = this;
  74231. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74232. if (!cams) {
  74233. return;
  74234. }
  74235. for (var i = 0; i < cams.length; i++) {
  74236. var camera = cams[i];
  74237. var cameraName = camera.name;
  74238. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  74239. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  74240. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74241. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  74242. });
  74243. }
  74244. }
  74245. }
  74246. };
  74247. /**
  74248. * Disables the effect on the given cameras
  74249. * @param cameras The camera to disable.
  74250. */
  74251. PostProcessRenderEffect.prototype._disable = function (cameras) {
  74252. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74253. if (!cams) {
  74254. return;
  74255. }
  74256. for (var i = 0; i < cams.length; i++) {
  74257. var camera = cams[i];
  74258. var cameraName = camera.name;
  74259. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74260. camera.detachPostProcess(postProcess);
  74261. });
  74262. }
  74263. };
  74264. /**
  74265. * Gets a list of the post processes contained in the effect.
  74266. * @param camera The camera to get the post processes on.
  74267. * @returns The list of the post processes in the effect.
  74268. */
  74269. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  74270. if (this._singleInstance) {
  74271. return this._postProcesses[0];
  74272. }
  74273. else {
  74274. if (!camera) {
  74275. return null;
  74276. }
  74277. return this._postProcesses[camera.name];
  74278. }
  74279. };
  74280. return PostProcessRenderEffect;
  74281. }());
  74282. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  74283. })(BABYLON || (BABYLON = {}));
  74284. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  74285. var BABYLON;
  74286. (function (BABYLON) {
  74287. var PostProcessRenderPipeline = /** @class */ (function () {
  74288. function PostProcessRenderPipeline(engine, name) {
  74289. this.engine = engine;
  74290. this._name = name;
  74291. this._renderEffects = {};
  74292. this._renderEffectsForIsolatedPass = new Array();
  74293. this._cameras = [];
  74294. }
  74295. PostProcessRenderPipeline.prototype.getClassName = function () {
  74296. return "PostProcessRenderPipeline";
  74297. };
  74298. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  74299. get: function () {
  74300. for (var renderEffectName in this._renderEffects) {
  74301. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74302. if (!this._renderEffects[renderEffectName].isSupported) {
  74303. return false;
  74304. }
  74305. }
  74306. }
  74307. return true;
  74308. },
  74309. enumerable: true,
  74310. configurable: true
  74311. });
  74312. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  74313. this._renderEffects[renderEffect._name] = renderEffect;
  74314. };
  74315. // private
  74316. PostProcessRenderPipeline.prototype._rebuild = function () {
  74317. };
  74318. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  74319. var renderEffects = this._renderEffects[renderEffectName];
  74320. if (!renderEffects) {
  74321. return;
  74322. }
  74323. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74324. };
  74325. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  74326. var renderEffects = this._renderEffects[renderEffectName];
  74327. if (!renderEffects) {
  74328. return;
  74329. }
  74330. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74331. };
  74332. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  74333. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74334. if (!cams) {
  74335. return;
  74336. }
  74337. var indicesToDelete = [];
  74338. var i;
  74339. for (i = 0; i < cams.length; i++) {
  74340. var camera = cams[i];
  74341. var cameraName = camera.name;
  74342. if (this._cameras.indexOf(camera) === -1) {
  74343. this._cameras[cameraName] = camera;
  74344. }
  74345. else if (unique) {
  74346. indicesToDelete.push(i);
  74347. }
  74348. }
  74349. for (i = 0; i < indicesToDelete.length; i++) {
  74350. cameras.splice(indicesToDelete[i], 1);
  74351. }
  74352. for (var renderEffectName in this._renderEffects) {
  74353. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74354. this._renderEffects[renderEffectName]._attachCameras(cams);
  74355. }
  74356. }
  74357. };
  74358. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  74359. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74360. if (!cams) {
  74361. return;
  74362. }
  74363. for (var renderEffectName in this._renderEffects) {
  74364. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74365. this._renderEffects[renderEffectName]._detachCameras(cams);
  74366. }
  74367. }
  74368. for (var i = 0; i < cams.length; i++) {
  74369. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  74370. }
  74371. };
  74372. PostProcessRenderPipeline.prototype._update = function () {
  74373. for (var renderEffectName in this._renderEffects) {
  74374. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74375. this._renderEffects[renderEffectName]._update();
  74376. }
  74377. }
  74378. for (var i = 0; i < this._cameras.length; i++) {
  74379. var cameraName = this._cameras[i].name;
  74380. if (this._renderEffectsForIsolatedPass[cameraName]) {
  74381. this._renderEffectsForIsolatedPass[cameraName]._update();
  74382. }
  74383. }
  74384. };
  74385. PostProcessRenderPipeline.prototype._reset = function () {
  74386. this._renderEffects = {};
  74387. this._renderEffectsForIsolatedPass = new Array();
  74388. };
  74389. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  74390. // 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)
  74391. var effectKeys = Object.keys(this._renderEffects);
  74392. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  74393. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  74394. if (postProcesses) {
  74395. postProcesses[0].samples = sampleCount;
  74396. return true;
  74397. }
  74398. }
  74399. return false;
  74400. };
  74401. PostProcessRenderPipeline.prototype.dispose = function () {
  74402. // Must be implemented by children
  74403. };
  74404. __decorate([
  74405. BABYLON.serialize()
  74406. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  74407. return PostProcessRenderPipeline;
  74408. }());
  74409. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  74410. })(BABYLON || (BABYLON = {}));
  74411. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  74412. var BABYLON;
  74413. (function (BABYLON) {
  74414. /**
  74415. * This represents a depth renderer in Babylon.
  74416. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  74417. */
  74418. var DepthRenderer = /** @class */ (function () {
  74419. /**
  74420. * Instantiates a depth renderer
  74421. * @param scene The scene the renderer belongs to
  74422. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  74423. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  74424. */
  74425. function DepthRenderer(scene, type, camera) {
  74426. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74427. if (camera === void 0) { camera = null; }
  74428. var _this = this;
  74429. this._scene = scene;
  74430. this._camera = camera;
  74431. var engine = scene.getEngine();
  74432. // Render target
  74433. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  74434. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74435. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74436. this._depthMap.refreshRate = 1;
  74437. this._depthMap.renderParticles = false;
  74438. this._depthMap.renderList = null;
  74439. // Camera to get depth map from to support multiple concurrent cameras
  74440. this._depthMap.activeCamera = this._camera;
  74441. this._depthMap.ignoreCameraViewport = true;
  74442. this._depthMap.useCameraPostProcesses = false;
  74443. // set default depth value to 1.0 (far away)
  74444. this._depthMap.onClearObservable.add(function (engine) {
  74445. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  74446. });
  74447. // Custom render function
  74448. var renderSubMesh = function (subMesh) {
  74449. var mesh = subMesh.getRenderingMesh();
  74450. var scene = _this._scene;
  74451. var engine = scene.getEngine();
  74452. var material = subMesh.getMaterial();
  74453. if (!material) {
  74454. return;
  74455. }
  74456. // Culling and reverse (right handed system)
  74457. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74458. // Managing instances
  74459. var batch = mesh._getInstancesRenderList(subMesh._id);
  74460. if (batch.mustReturn) {
  74461. return;
  74462. }
  74463. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74464. var camera = _this._camera || scene.activeCamera;
  74465. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  74466. engine.enableEffect(_this._effect);
  74467. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74468. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74469. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  74470. // Alpha test
  74471. if (material && material.needAlphaTesting()) {
  74472. var alphaTexture = material.getAlphaTestTexture();
  74473. if (alphaTexture) {
  74474. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74475. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74476. }
  74477. }
  74478. // Bones
  74479. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74480. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74481. }
  74482. // Draw
  74483. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74484. }
  74485. };
  74486. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74487. var index;
  74488. if (depthOnlySubMeshes.length) {
  74489. engine.setColorWrite(false);
  74490. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74491. renderSubMesh(depthOnlySubMeshes.data[index]);
  74492. }
  74493. engine.setColorWrite(true);
  74494. }
  74495. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74496. renderSubMesh(opaqueSubMeshes.data[index]);
  74497. }
  74498. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74499. renderSubMesh(alphaTestSubMeshes.data[index]);
  74500. }
  74501. };
  74502. }
  74503. /**
  74504. * Creates the depth rendering effect and checks if the effect is ready.
  74505. * @param subMesh The submesh to be used to render the depth map of
  74506. * @param useInstances If multiple world instances should be used
  74507. * @returns if the depth renderer is ready to render the depth map
  74508. */
  74509. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  74510. var material = subMesh.getMaterial();
  74511. if (material.disableDepthWrite) {
  74512. return false;
  74513. }
  74514. var defines = [];
  74515. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74516. var mesh = subMesh.getMesh();
  74517. // Alpha test
  74518. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  74519. defines.push("#define ALPHATEST");
  74520. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74521. attribs.push(BABYLON.VertexBuffer.UVKind);
  74522. defines.push("#define UV1");
  74523. }
  74524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74525. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74526. defines.push("#define UV2");
  74527. }
  74528. }
  74529. // Bones
  74530. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74531. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74532. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74533. if (mesh.numBoneInfluencers > 4) {
  74534. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74535. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74536. }
  74537. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74538. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74539. }
  74540. else {
  74541. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74542. }
  74543. // Instances
  74544. if (useInstances) {
  74545. defines.push("#define INSTANCES");
  74546. attribs.push("world0");
  74547. attribs.push("world1");
  74548. attribs.push("world2");
  74549. attribs.push("world3");
  74550. }
  74551. // Get correct effect
  74552. var join = defines.join("\n");
  74553. if (this._cachedDefines !== join) {
  74554. this._cachedDefines = join;
  74555. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  74556. }
  74557. return this._effect.isReady();
  74558. };
  74559. /**
  74560. * Gets the texture which the depth map will be written to.
  74561. * @returns The depth map texture
  74562. */
  74563. DepthRenderer.prototype.getDepthMap = function () {
  74564. return this._depthMap;
  74565. };
  74566. /**
  74567. * Disposes of the depth renderer.
  74568. */
  74569. DepthRenderer.prototype.dispose = function () {
  74570. this._depthMap.dispose();
  74571. };
  74572. return DepthRenderer;
  74573. }());
  74574. BABYLON.DepthRenderer = DepthRenderer;
  74575. })(BABYLON || (BABYLON = {}));
  74576. //# sourceMappingURL=babylon.depthRenderer.js.map
  74577. var BABYLON;
  74578. (function (BABYLON) {
  74579. var SSAORenderingPipeline = /** @class */ (function (_super) {
  74580. __extends(SSAORenderingPipeline, _super);
  74581. /**
  74582. * @constructor
  74583. * @param {string} name - The rendering pipeline name
  74584. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74585. * @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 }
  74586. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74587. */
  74588. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  74589. var _this = _super.call(this, scene.getEngine(), name) || this;
  74590. // Members
  74591. /**
  74592. * The PassPostProcess id in the pipeline that contains the original scene color
  74593. */
  74594. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74595. /**
  74596. * The SSAO PostProcess id in the pipeline
  74597. */
  74598. _this.SSAORenderEffect = "SSAORenderEffect";
  74599. /**
  74600. * The horizontal blur PostProcess id in the pipeline
  74601. */
  74602. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74603. /**
  74604. * The vertical blur PostProcess id in the pipeline
  74605. */
  74606. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74607. /**
  74608. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74609. */
  74610. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74611. /**
  74612. * The output strength of the SSAO post-process. Default value is 1.0.
  74613. */
  74614. _this.totalStrength = 1.0;
  74615. /**
  74616. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  74617. */
  74618. _this.radius = 0.0001;
  74619. /**
  74620. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  74621. * Must not be equal to fallOff and superior to fallOff.
  74622. * Default value is 0.975
  74623. */
  74624. _this.area = 0.0075;
  74625. /**
  74626. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  74627. * Must not be equal to area and inferior to area.
  74628. * Default value is 0.0
  74629. */
  74630. _this.fallOff = 0.000001;
  74631. /**
  74632. * The base color of the SSAO post-process
  74633. * The final result is "base + ssao" between [0, 1]
  74634. */
  74635. _this.base = 0.5;
  74636. _this._firstUpdate = true;
  74637. _this._scene = scene;
  74638. // Set up assets
  74639. _this._createRandomTexture();
  74640. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74641. var ssaoRatio = ratio.ssaoRatio || ratio;
  74642. var combineRatio = ratio.combineRatio || ratio;
  74643. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74644. _this._createSSAOPostProcess(ssaoRatio);
  74645. _this._createBlurPostProcess(ssaoRatio);
  74646. _this._createSSAOCombinePostProcess(combineRatio);
  74647. // Set up pipeline
  74648. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74649. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74650. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74651. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74652. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74653. // Finish
  74654. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74655. if (cameras)
  74656. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74657. return _this;
  74658. }
  74659. // Public Methods
  74660. /**
  74661. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74662. */
  74663. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74664. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74665. for (var i = 0; i < this._scene.cameras.length; i++) {
  74666. var camera = this._scene.cameras[i];
  74667. this._originalColorPostProcess.dispose(camera);
  74668. this._ssaoPostProcess.dispose(camera);
  74669. this._blurHPostProcess.dispose(camera);
  74670. this._blurVPostProcess.dispose(camera);
  74671. this._ssaoCombinePostProcess.dispose(camera);
  74672. }
  74673. this._randomTexture.dispose();
  74674. if (disableDepthRender)
  74675. this._scene.disableDepthRenderer();
  74676. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74677. _super.prototype.dispose.call(this);
  74678. };
  74679. // Private Methods
  74680. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  74681. var _this = this;
  74682. var size = 16;
  74683. 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);
  74684. 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);
  74685. this._blurHPostProcess.onActivateObservable.add(function () {
  74686. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  74687. _this._blurHPostProcess.kernel = size * dw;
  74688. });
  74689. this._blurVPostProcess.onActivateObservable.add(function () {
  74690. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  74691. _this._blurVPostProcess.kernel = size * dw;
  74692. });
  74693. };
  74694. SSAORenderingPipeline.prototype._rebuild = function () {
  74695. this._firstUpdate = true;
  74696. _super.prototype._rebuild.call(this);
  74697. };
  74698. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74699. var _this = this;
  74700. var numSamples = 16;
  74701. var sampleSphere = [
  74702. 0.5381, 0.1856, -0.4319,
  74703. 0.1379, 0.2486, 0.4430,
  74704. 0.3371, 0.5679, -0.0057,
  74705. -0.6999, -0.0451, -0.0019,
  74706. 0.0689, -0.1598, -0.8547,
  74707. 0.0560, 0.0069, -0.1843,
  74708. -0.0146, 0.1402, 0.0762,
  74709. 0.0100, -0.1924, -0.0344,
  74710. -0.3577, -0.5301, -0.4358,
  74711. -0.3169, 0.1063, 0.0158,
  74712. 0.0103, -0.5869, 0.0046,
  74713. -0.0897, -0.4940, 0.3287,
  74714. 0.7119, -0.0154, -0.0918,
  74715. -0.0533, 0.0596, -0.5411,
  74716. 0.0352, -0.0631, 0.5460,
  74717. -0.4776, 0.2847, -0.0271
  74718. ];
  74719. var samplesFactor = 1.0 / numSamples;
  74720. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74721. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74722. "area", "fallOff", "base", "range", "viewport"
  74723. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74724. this._ssaoPostProcess.onApply = function (effect) {
  74725. if (_this._firstUpdate) {
  74726. effect.setArray3("sampleSphere", sampleSphere);
  74727. effect.setFloat("samplesFactor", samplesFactor);
  74728. effect.setFloat("randTextureTiles", 4.0);
  74729. }
  74730. effect.setFloat("totalStrength", _this.totalStrength);
  74731. effect.setFloat("radius", _this.radius);
  74732. effect.setFloat("area", _this.area);
  74733. effect.setFloat("fallOff", _this.fallOff);
  74734. effect.setFloat("base", _this.base);
  74735. effect.setTexture("textureSampler", _this._depthTexture);
  74736. effect.setTexture("randomSampler", _this._randomTexture);
  74737. };
  74738. };
  74739. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74740. var _this = this;
  74741. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74742. this._ssaoCombinePostProcess.onApply = function (effect) {
  74743. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74744. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74745. };
  74746. };
  74747. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74748. var size = 512;
  74749. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74750. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74751. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74752. var context = this._randomTexture.getContext();
  74753. var rand = function (min, max) {
  74754. return Math.random() * (max - min) + min;
  74755. };
  74756. var randVector = BABYLON.Vector3.Zero();
  74757. for (var x = 0; x < size; x++) {
  74758. for (var y = 0; y < size; y++) {
  74759. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74760. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74761. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74762. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74763. context.fillRect(x, y, 1, 1);
  74764. }
  74765. }
  74766. this._randomTexture.update(false);
  74767. };
  74768. __decorate([
  74769. BABYLON.serialize()
  74770. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74771. __decorate([
  74772. BABYLON.serialize()
  74773. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74774. __decorate([
  74775. BABYLON.serialize()
  74776. ], SSAORenderingPipeline.prototype, "area", void 0);
  74777. __decorate([
  74778. BABYLON.serialize()
  74779. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74780. __decorate([
  74781. BABYLON.serialize()
  74782. ], SSAORenderingPipeline.prototype, "base", void 0);
  74783. return SSAORenderingPipeline;
  74784. }(BABYLON.PostProcessRenderPipeline));
  74785. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74786. })(BABYLON || (BABYLON = {}));
  74787. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74788. var BABYLON;
  74789. (function (BABYLON) {
  74790. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74791. __extends(SSAO2RenderingPipeline, _super);
  74792. /**
  74793. * @constructor
  74794. * @param {string} name - The rendering pipeline name
  74795. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74796. * @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 }
  74797. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74798. */
  74799. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74800. var _this = _super.call(this, scene.getEngine(), name) || this;
  74801. // Members
  74802. /**
  74803. * The PassPostProcess id in the pipeline that contains the original scene color
  74804. */
  74805. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74806. /**
  74807. * The SSAO PostProcess id in the pipeline
  74808. */
  74809. _this.SSAORenderEffect = "SSAORenderEffect";
  74810. /**
  74811. * The horizontal blur PostProcess id in the pipeline
  74812. */
  74813. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74814. /**
  74815. * The vertical blur PostProcess id in the pipeline
  74816. */
  74817. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74818. /**
  74819. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74820. */
  74821. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74822. /**
  74823. * The output strength of the SSAO post-process. Default value is 1.0.
  74824. */
  74825. _this.totalStrength = 1.0;
  74826. /**
  74827. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74828. */
  74829. _this.maxZ = 100.0;
  74830. /**
  74831. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74832. */
  74833. _this.minZAspect = 0.2;
  74834. /**
  74835. * Number of samples used for the SSAO calculations. Default value is 8
  74836. */
  74837. _this._samples = 8;
  74838. /**
  74839. * Are we using bilateral blur ?
  74840. */
  74841. _this._expensiveBlur = true;
  74842. /**
  74843. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74844. */
  74845. _this.radius = 2.0;
  74846. /**
  74847. * The base color of the SSAO post-process
  74848. * The final result is "base + ssao" between [0, 1]
  74849. */
  74850. _this.base = 0.1;
  74851. _this._firstUpdate = true;
  74852. _this._scene = scene;
  74853. _this._ratio = ratio;
  74854. if (!_this.isSupported) {
  74855. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74856. return _this;
  74857. }
  74858. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74859. var blurRatio = _this._ratio.blurRatio || ratio;
  74860. // Set up assets
  74861. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74862. _this._createRandomTexture();
  74863. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74864. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74865. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74866. _this._createSSAOPostProcess(1.0);
  74867. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74868. _this._createSSAOCombinePostProcess(blurRatio);
  74869. // Set up pipeline
  74870. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74871. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74872. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74873. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74874. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74875. // Finish
  74876. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74877. if (cameras)
  74878. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74879. return _this;
  74880. }
  74881. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74882. get: function () {
  74883. return this._samples;
  74884. },
  74885. set: function (n) {
  74886. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74887. this._samples = n;
  74888. this._sampleSphere = this._generateHemisphere();
  74889. this._firstUpdate = true;
  74890. },
  74891. enumerable: true,
  74892. configurable: true
  74893. });
  74894. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74895. get: function () {
  74896. return this._expensiveBlur;
  74897. },
  74898. set: function (b) {
  74899. 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"]);
  74900. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74901. this._expensiveBlur = b;
  74902. this._firstUpdate = true;
  74903. },
  74904. enumerable: true,
  74905. configurable: true
  74906. });
  74907. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74908. /**
  74909. * Support test.
  74910. */
  74911. get: function () {
  74912. var engine = BABYLON.Engine.LastCreatedEngine;
  74913. if (!engine) {
  74914. return false;
  74915. }
  74916. return engine.getCaps().drawBuffersExtension;
  74917. },
  74918. enumerable: true,
  74919. configurable: true
  74920. });
  74921. // Public Methods
  74922. /**
  74923. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74924. */
  74925. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74926. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74927. for (var i = 0; i < this._scene.cameras.length; i++) {
  74928. var camera = this._scene.cameras[i];
  74929. this._originalColorPostProcess.dispose(camera);
  74930. this._ssaoPostProcess.dispose(camera);
  74931. this._blurHPostProcess.dispose(camera);
  74932. this._blurVPostProcess.dispose(camera);
  74933. this._ssaoCombinePostProcess.dispose(camera);
  74934. }
  74935. this._randomTexture.dispose();
  74936. if (disableGeometryBufferRenderer)
  74937. this._scene.disableGeometryBufferRenderer();
  74938. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74939. _super.prototype.dispose.call(this);
  74940. };
  74941. // Private Methods
  74942. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74943. var _this = this;
  74944. this._samplerOffsets = [];
  74945. var expensive = this.expensiveBlur;
  74946. for (var i = -8; i < 8; i++) {
  74947. this._samplerOffsets.push(i * 2 + 0.5);
  74948. }
  74949. 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");
  74950. this._blurHPostProcess.onApply = function (effect) {
  74951. if (!_this._scene.activeCamera) {
  74952. return;
  74953. }
  74954. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74955. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74956. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74957. effect.setFloat("radius", _this.radius);
  74958. effect.setTexture("depthSampler", _this._depthTexture);
  74959. if (_this._firstUpdate) {
  74960. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74961. }
  74962. };
  74963. 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");
  74964. this._blurVPostProcess.onApply = function (effect) {
  74965. if (!_this._scene.activeCamera) {
  74966. return;
  74967. }
  74968. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74969. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74970. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74971. effect.setFloat("radius", _this.radius);
  74972. effect.setTexture("depthSampler", _this._depthTexture);
  74973. if (_this._firstUpdate) {
  74974. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74975. _this._firstUpdate = false;
  74976. }
  74977. };
  74978. };
  74979. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74980. this._firstUpdate = true;
  74981. _super.prototype._rebuild.call(this);
  74982. };
  74983. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74984. var numSamples = this.samples;
  74985. var result = [];
  74986. var vector, scale;
  74987. var rand = function (min, max) {
  74988. return Math.random() * (max - min) + min;
  74989. };
  74990. var i = 0;
  74991. while (i < numSamples) {
  74992. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74993. vector.normalize();
  74994. scale = i / numSamples;
  74995. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74996. vector.scaleInPlace(scale);
  74997. result.push(vector.x, vector.y, vector.z);
  74998. i++;
  74999. }
  75000. return result;
  75001. };
  75002. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75003. var _this = this;
  75004. var numSamples = this.samples;
  75005. this._sampleSphere = this._generateHemisphere();
  75006. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75007. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75008. "base", "range", "projection", "near", "far", "texelSize",
  75009. "xViewport", "yViewport", "maxZ", "minZAspect"
  75010. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75011. this._ssaoPostProcess.onApply = function (effect) {
  75012. if (_this._firstUpdate) {
  75013. effect.setArray3("sampleSphere", _this._sampleSphere);
  75014. effect.setFloat("randTextureTiles", 4.0);
  75015. }
  75016. if (!_this._scene.activeCamera) {
  75017. return;
  75018. }
  75019. effect.setFloat("samplesFactor", 1 / _this.samples);
  75020. effect.setFloat("totalStrength", _this.totalStrength);
  75021. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75022. effect.setFloat("radius", _this.radius);
  75023. effect.setFloat("maxZ", _this.maxZ);
  75024. effect.setFloat("minZAspect", _this.minZAspect);
  75025. effect.setFloat("base", _this.base);
  75026. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75027. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75028. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75029. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75030. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75031. effect.setTexture("textureSampler", _this._depthTexture);
  75032. effect.setTexture("normalSampler", _this._normalTexture);
  75033. effect.setTexture("randomSampler", _this._randomTexture);
  75034. };
  75035. };
  75036. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75037. var _this = this;
  75038. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75039. this._ssaoCombinePostProcess.onApply = function (effect) {
  75040. var viewport = _this._scene.activeCamera.viewport;
  75041. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75042. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75043. };
  75044. };
  75045. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75046. var size = 512;
  75047. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75048. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75049. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75050. var context = this._randomTexture.getContext();
  75051. var rand = function (min, max) {
  75052. return Math.random() * (max - min) + min;
  75053. };
  75054. var randVector = BABYLON.Vector3.Zero();
  75055. for (var x = 0; x < size; x++) {
  75056. for (var y = 0; y < size; y++) {
  75057. randVector.x = rand(0.0, 1.0);
  75058. randVector.y = rand(0.0, 1.0);
  75059. randVector.z = 0.0;
  75060. randVector.normalize();
  75061. randVector.scaleInPlace(255);
  75062. randVector.x = Math.floor(randVector.x);
  75063. randVector.y = Math.floor(randVector.y);
  75064. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75065. context.fillRect(x, y, 1, 1);
  75066. }
  75067. }
  75068. this._randomTexture.update(false);
  75069. };
  75070. /**
  75071. * Serialize the rendering pipeline (Used when exporting)
  75072. * @returns the serialized object
  75073. */
  75074. SSAO2RenderingPipeline.prototype.serialize = function () {
  75075. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75076. serializationObject.customType = "SSAO2RenderingPipeline";
  75077. return serializationObject;
  75078. };
  75079. /**
  75080. * Parse the serialized pipeline
  75081. * @param source Source pipeline.
  75082. * @param scene The scene to load the pipeline to.
  75083. * @param rootUrl The URL of the serialized pipeline.
  75084. * @returns An instantiated pipeline from the serialized object.
  75085. */
  75086. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  75087. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75088. };
  75089. __decorate([
  75090. BABYLON.serialize()
  75091. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  75092. __decorate([
  75093. BABYLON.serialize()
  75094. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  75095. __decorate([
  75096. BABYLON.serialize()
  75097. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  75098. __decorate([
  75099. BABYLON.serialize("samples")
  75100. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  75101. __decorate([
  75102. BABYLON.serialize()
  75103. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  75104. __decorate([
  75105. BABYLON.serialize("expensiveBlur")
  75106. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  75107. __decorate([
  75108. BABYLON.serialize()
  75109. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  75110. __decorate([
  75111. BABYLON.serialize()
  75112. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  75113. return SSAO2RenderingPipeline;
  75114. }(BABYLON.PostProcessRenderPipeline));
  75115. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  75116. })(BABYLON || (BABYLON = {}));
  75117. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  75118. // BABYLON.JS Chromatic Aberration GLSL Shader
  75119. // Author: Olivier Guyot
  75120. // Separates very slightly R, G and B colors on the edges of the screen
  75121. // Inspired by Francois Tarlier & Martins Upitis
  75122. var BABYLON;
  75123. (function (BABYLON) {
  75124. var LensRenderingPipeline = /** @class */ (function (_super) {
  75125. __extends(LensRenderingPipeline, _super);
  75126. /**
  75127. * @constructor
  75128. *
  75129. * Effect parameters are as follow:
  75130. * {
  75131. * chromatic_aberration: number; // from 0 to x (1 for realism)
  75132. * edge_blur: number; // from 0 to x (1 for realism)
  75133. * distortion: number; // from 0 to x (1 for realism)
  75134. * grain_amount: number; // from 0 to 1
  75135. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  75136. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  75137. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  75138. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  75139. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  75140. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  75141. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  75142. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  75143. * }
  75144. * Note: if an effect parameter is unset, effect is disabled
  75145. *
  75146. * @param {string} name - The rendering pipeline name
  75147. * @param {object} parameters - An object containing all parameters (see above)
  75148. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75149. * @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)
  75150. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75151. */
  75152. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  75153. if (ratio === void 0) { ratio = 1.0; }
  75154. var _this = _super.call(this, scene.getEngine(), name) || this;
  75155. // Lens effects can be of the following:
  75156. // - chromatic aberration (slight shift of RGB colors)
  75157. // - blur on the edge of the lens
  75158. // - lens distortion
  75159. // - depth-of-field blur & highlights enhancing
  75160. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  75161. // - grain effect (noise or custom texture)
  75162. // Two additional texture samplers are needed:
  75163. // - depth map (for depth-of-field)
  75164. // - grain texture
  75165. /**
  75166. * The chromatic aberration PostProcess id in the pipeline
  75167. */
  75168. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  75169. /**
  75170. * The highlights enhancing PostProcess id in the pipeline
  75171. */
  75172. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  75173. /**
  75174. * The depth-of-field PostProcess id in the pipeline
  75175. */
  75176. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  75177. _this._scene = scene;
  75178. // Fetch texture samplers
  75179. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75180. if (parameters.grain_texture) {
  75181. _this._grainTexture = parameters.grain_texture;
  75182. }
  75183. else {
  75184. _this._createGrainTexture();
  75185. }
  75186. // save parameters
  75187. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  75188. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  75189. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  75190. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  75191. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  75192. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  75193. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  75194. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  75195. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  75196. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  75197. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  75198. // Create effects
  75199. _this._createChromaticAberrationPostProcess(ratio);
  75200. _this._createHighlightsPostProcess(ratio);
  75201. _this._createDepthOfFieldPostProcess(ratio / 4);
  75202. // Set up pipeline
  75203. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  75204. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  75205. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  75206. if (_this._highlightsGain === -1) {
  75207. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  75208. }
  75209. // Finish
  75210. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75211. if (cameras) {
  75212. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75213. }
  75214. return _this;
  75215. }
  75216. // public methods (self explanatory)
  75217. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  75218. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  75219. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  75220. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  75221. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  75222. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  75223. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  75224. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  75225. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  75226. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  75227. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  75228. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  75229. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  75230. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  75231. };
  75232. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  75233. this._highlightsPostProcess.updateEffect();
  75234. };
  75235. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  75236. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  75237. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  75238. this._highlightsGain = amount;
  75239. };
  75240. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  75241. if (this._highlightsGain === -1) {
  75242. this._highlightsGain = 1.0;
  75243. }
  75244. this._highlightsThreshold = amount;
  75245. };
  75246. LensRenderingPipeline.prototype.disableHighlights = function () {
  75247. this._highlightsGain = -1;
  75248. };
  75249. /**
  75250. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  75251. */
  75252. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75253. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75254. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75255. this._chromaticAberrationPostProcess = null;
  75256. this._highlightsPostProcess = null;
  75257. this._depthOfFieldPostProcess = null;
  75258. this._grainTexture.dispose();
  75259. if (disableDepthRender)
  75260. this._scene.disableDepthRenderer();
  75261. };
  75262. // colors shifting and distortion
  75263. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  75264. var _this = this;
  75265. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  75266. [], // samplers
  75267. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75268. this._chromaticAberrationPostProcess.onApply = function (effect) {
  75269. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  75270. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75271. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75272. effect.setFloat('radialIntensity', 1);
  75273. effect.setFloat2('direction', 17, 17);
  75274. effect.setFloat2('centerPosition', 0.5, 0.5);
  75275. };
  75276. };
  75277. // highlights enhancing
  75278. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  75279. var _this = this;
  75280. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  75281. [], // samplers
  75282. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  75283. this._highlightsPostProcess.onApply = function (effect) {
  75284. effect.setFloat('gain', _this._highlightsGain);
  75285. effect.setFloat('threshold', _this._highlightsThreshold);
  75286. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  75287. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75288. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75289. };
  75290. };
  75291. // colors shifting and distortion
  75292. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  75293. var _this = this;
  75294. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  75295. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  75296. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  75297. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75298. this._depthOfFieldPostProcess.onApply = function (effect) {
  75299. effect.setTexture("depthSampler", _this._depthTexture);
  75300. effect.setTexture("grainSampler", _this._grainTexture);
  75301. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  75302. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  75303. effect.setFloat('grain_amount', _this._grainAmount);
  75304. effect.setBool('blur_noise', _this._blurNoise);
  75305. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75306. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75307. effect.setFloat('distortion', _this._distortion);
  75308. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  75309. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  75310. effect.setFloat('aperture', _this._dofAperture);
  75311. effect.setFloat('darken', _this._dofDarken);
  75312. effect.setFloat('edge_blur', _this._edgeBlur);
  75313. effect.setBool('highlights', (_this._highlightsGain !== -1));
  75314. if (_this._scene.activeCamera) {
  75315. effect.setFloat('near', _this._scene.activeCamera.minZ);
  75316. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  75317. }
  75318. };
  75319. };
  75320. // creates a black and white random noise texture, 512x512
  75321. LensRenderingPipeline.prototype._createGrainTexture = function () {
  75322. var size = 512;
  75323. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75324. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75325. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75326. var context = this._grainTexture.getContext();
  75327. var rand = function (min, max) {
  75328. return Math.random() * (max - min) + min;
  75329. };
  75330. var value;
  75331. for (var x = 0; x < size; x++) {
  75332. for (var y = 0; y < size; y++) {
  75333. value = Math.floor(rand(0.42, 0.58) * 255);
  75334. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  75335. context.fillRect(x, y, 1, 1);
  75336. }
  75337. }
  75338. this._grainTexture.update(false);
  75339. };
  75340. return LensRenderingPipeline;
  75341. }(BABYLON.PostProcessRenderPipeline));
  75342. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  75343. })(BABYLON || (BABYLON = {}));
  75344. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  75345. var BABYLON;
  75346. (function (BABYLON) {
  75347. var StandardRenderingPipeline = /** @class */ (function (_super) {
  75348. __extends(StandardRenderingPipeline, _super);
  75349. /**
  75350. * @constructor
  75351. * @param {string} name - The rendering pipeline name
  75352. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75353. * @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)
  75354. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  75355. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75356. */
  75357. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  75358. if (originalPostProcess === void 0) { originalPostProcess = null; }
  75359. var _this = _super.call(this, scene.getEngine(), name) || this;
  75360. _this.downSampleX4PostProcess = null;
  75361. _this.brightPassPostProcess = null;
  75362. _this.blurHPostProcesses = [];
  75363. _this.blurVPostProcesses = [];
  75364. _this.textureAdderPostProcess = null;
  75365. _this.volumetricLightPostProcess = null;
  75366. _this.volumetricLightSmoothXPostProcess = null;
  75367. _this.volumetricLightSmoothYPostProcess = null;
  75368. _this.volumetricLightMergePostProces = null;
  75369. _this.volumetricLightFinalPostProcess = null;
  75370. _this.luminancePostProcess = null;
  75371. _this.luminanceDownSamplePostProcesses = [];
  75372. _this.hdrPostProcess = null;
  75373. _this.textureAdderFinalPostProcess = null;
  75374. _this.lensFlareFinalPostProcess = null;
  75375. _this.hdrFinalPostProcess = null;
  75376. _this.lensFlarePostProcess = null;
  75377. _this.lensFlareComposePostProcess = null;
  75378. _this.motionBlurPostProcess = null;
  75379. _this.depthOfFieldPostProcess = null;
  75380. // Values
  75381. _this.brightThreshold = 1.0;
  75382. _this.blurWidth = 512.0;
  75383. _this.horizontalBlur = false;
  75384. _this.exposure = 1.0;
  75385. _this.lensTexture = null;
  75386. _this.volumetricLightCoefficient = 0.2;
  75387. _this.volumetricLightPower = 4.0;
  75388. _this.volumetricLightBlurScale = 64.0;
  75389. _this.sourceLight = null;
  75390. _this.hdrMinimumLuminance = 1.0;
  75391. _this.hdrDecreaseRate = 0.5;
  75392. _this.hdrIncreaseRate = 0.5;
  75393. _this.lensColorTexture = null;
  75394. _this.lensFlareStrength = 20.0;
  75395. _this.lensFlareGhostDispersal = 1.4;
  75396. _this.lensFlareHaloWidth = 0.7;
  75397. _this.lensFlareDistortionStrength = 16.0;
  75398. _this.lensStarTexture = null;
  75399. _this.lensFlareDirtTexture = null;
  75400. _this.depthOfFieldDistance = 10.0;
  75401. _this.depthOfFieldBlurWidth = 64.0;
  75402. _this.motionStrength = 1.0;
  75403. // IAnimatable
  75404. _this.animations = [];
  75405. _this._currentDepthOfFieldSource = null;
  75406. _this._hdrCurrentLuminance = 1.0;
  75407. // Getters and setters
  75408. _this._bloomEnabled = true;
  75409. _this._depthOfFieldEnabled = false;
  75410. _this._vlsEnabled = false;
  75411. _this._lensFlareEnabled = false;
  75412. _this._hdrEnabled = false;
  75413. _this._motionBlurEnabled = false;
  75414. _this._motionBlurSamples = 64.0;
  75415. _this._volumetricLightStepsCount = 50.0;
  75416. _this._cameras = cameras || [];
  75417. // Initialize
  75418. _this._scene = scene;
  75419. _this._basePostProcess = originalPostProcess;
  75420. _this._ratio = ratio;
  75421. // Misc
  75422. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75423. // Finish
  75424. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75425. _this._buildPipeline();
  75426. return _this;
  75427. }
  75428. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  75429. get: function () {
  75430. return this._bloomEnabled;
  75431. },
  75432. set: function (enabled) {
  75433. if (this._bloomEnabled === enabled) {
  75434. return;
  75435. }
  75436. this._bloomEnabled = enabled;
  75437. this._buildPipeline();
  75438. },
  75439. enumerable: true,
  75440. configurable: true
  75441. });
  75442. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  75443. get: function () {
  75444. return this._depthOfFieldEnabled;
  75445. },
  75446. set: function (enabled) {
  75447. if (this._depthOfFieldEnabled === enabled) {
  75448. return;
  75449. }
  75450. this._depthOfFieldEnabled = enabled;
  75451. this._buildPipeline();
  75452. },
  75453. enumerable: true,
  75454. configurable: true
  75455. });
  75456. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  75457. get: function () {
  75458. return this._lensFlareEnabled;
  75459. },
  75460. set: function (enabled) {
  75461. if (this._lensFlareEnabled === enabled) {
  75462. return;
  75463. }
  75464. this._lensFlareEnabled = enabled;
  75465. this._buildPipeline();
  75466. },
  75467. enumerable: true,
  75468. configurable: true
  75469. });
  75470. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  75471. get: function () {
  75472. return this._hdrEnabled;
  75473. },
  75474. set: function (enabled) {
  75475. if (this._hdrEnabled === enabled) {
  75476. return;
  75477. }
  75478. this._hdrEnabled = enabled;
  75479. this._buildPipeline();
  75480. },
  75481. enumerable: true,
  75482. configurable: true
  75483. });
  75484. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  75485. get: function () {
  75486. return this._vlsEnabled;
  75487. },
  75488. set: function (enabled) {
  75489. if (this._vlsEnabled === enabled) {
  75490. return;
  75491. }
  75492. if (enabled) {
  75493. var geometry = this._scene.enableGeometryBufferRenderer();
  75494. if (!geometry) {
  75495. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  75496. return;
  75497. }
  75498. }
  75499. this._vlsEnabled = enabled;
  75500. this._buildPipeline();
  75501. },
  75502. enumerable: true,
  75503. configurable: true
  75504. });
  75505. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  75506. get: function () {
  75507. return this._motionBlurEnabled;
  75508. },
  75509. set: function (enabled) {
  75510. if (this._motionBlurEnabled === enabled) {
  75511. return;
  75512. }
  75513. this._motionBlurEnabled = enabled;
  75514. this._buildPipeline();
  75515. },
  75516. enumerable: true,
  75517. configurable: true
  75518. });
  75519. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  75520. get: function () {
  75521. return this._volumetricLightStepsCount;
  75522. },
  75523. set: function (count) {
  75524. if (this.volumetricLightPostProcess) {
  75525. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  75526. }
  75527. this._volumetricLightStepsCount = count;
  75528. },
  75529. enumerable: true,
  75530. configurable: true
  75531. });
  75532. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  75533. get: function () {
  75534. return this._motionBlurSamples;
  75535. },
  75536. set: function (samples) {
  75537. if (this.motionBlurPostProcess) {
  75538. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  75539. }
  75540. this._motionBlurSamples = samples;
  75541. },
  75542. enumerable: true,
  75543. configurable: true
  75544. });
  75545. StandardRenderingPipeline.prototype._buildPipeline = function () {
  75546. var _this = this;
  75547. var ratio = this._ratio;
  75548. var scene = this._scene;
  75549. this._disposePostProcesses();
  75550. this._reset();
  75551. // Create pass post-process
  75552. if (!this._basePostProcess) {
  75553. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  75554. this.originalPostProcess.onApply = function (effect) {
  75555. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  75556. };
  75557. }
  75558. else {
  75559. this.originalPostProcess = this._basePostProcess;
  75560. }
  75561. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  75562. this._currentDepthOfFieldSource = this.originalPostProcess;
  75563. if (this._bloomEnabled) {
  75564. // Create down sample X4 post-process
  75565. this._createDownSampleX4PostProcess(scene, ratio / 2);
  75566. // Create bright pass post-process
  75567. this._createBrightPassPostProcess(scene, ratio / 2);
  75568. // Create gaussian blur post-processes (down sampling blurs)
  75569. this._createBlurPostProcesses(scene, ratio / 4, 1);
  75570. // Create texture adder post-process
  75571. this._createTextureAdderPostProcess(scene, ratio);
  75572. // Create depth-of-field source post-process
  75573. 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);
  75574. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  75575. }
  75576. if (this._vlsEnabled) {
  75577. // Create volumetric light
  75578. this._createVolumetricLightPostProcess(scene, ratio);
  75579. // Create volumetric light final post-process
  75580. 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);
  75581. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  75582. }
  75583. if (this._lensFlareEnabled) {
  75584. // Create lens flare post-process
  75585. this._createLensFlarePostProcess(scene, ratio);
  75586. // Create depth-of-field source post-process post lens-flare and disable it now
  75587. 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);
  75588. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  75589. }
  75590. if (this._hdrEnabled) {
  75591. // Create luminance
  75592. this._createLuminancePostProcesses(scene, this._floatTextureType);
  75593. // Create HDR
  75594. this._createHdrPostProcess(scene, ratio);
  75595. // Create depth-of-field source post-process post hdr and disable it now
  75596. 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);
  75597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  75598. }
  75599. if (this._depthOfFieldEnabled) {
  75600. // Create gaussian blur used by depth-of-field
  75601. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  75602. // Create depth-of-field post-process
  75603. this._createDepthOfFieldPostProcess(scene, ratio);
  75604. }
  75605. if (this._motionBlurEnabled) {
  75606. // Create motion blur post-process
  75607. this._createMotionBlurPostProcess(scene, ratio);
  75608. }
  75609. if (this._cameras !== null) {
  75610. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75611. }
  75612. };
  75613. // Down Sample X4 Post-Processs
  75614. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  75615. var _this = this;
  75616. var downSampleX4Offsets = new Array(32);
  75617. 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);
  75618. this.downSampleX4PostProcess.onApply = function (effect) {
  75619. var id = 0;
  75620. var width = _this.downSampleX4PostProcess.width;
  75621. var height = _this.downSampleX4PostProcess.height;
  75622. for (var i = -2; i < 2; i++) {
  75623. for (var j = -2; j < 2; j++) {
  75624. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  75625. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  75626. id += 2;
  75627. }
  75628. }
  75629. effect.setArray2("dsOffsets", downSampleX4Offsets);
  75630. };
  75631. // Add to pipeline
  75632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  75633. };
  75634. // Brightpass Post-Process
  75635. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  75636. var _this = this;
  75637. var brightOffsets = new Array(8);
  75638. 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);
  75639. this.brightPassPostProcess.onApply = function (effect) {
  75640. var sU = (1.0 / _this.brightPassPostProcess.width);
  75641. var sV = (1.0 / _this.brightPassPostProcess.height);
  75642. brightOffsets[0] = -0.5 * sU;
  75643. brightOffsets[1] = 0.5 * sV;
  75644. brightOffsets[2] = 0.5 * sU;
  75645. brightOffsets[3] = 0.5 * sV;
  75646. brightOffsets[4] = -0.5 * sU;
  75647. brightOffsets[5] = -0.5 * sV;
  75648. brightOffsets[6] = 0.5 * sU;
  75649. brightOffsets[7] = -0.5 * sV;
  75650. effect.setArray2("dsOffsets", brightOffsets);
  75651. effect.setFloat("brightThreshold", _this.brightThreshold);
  75652. };
  75653. // Add to pipeline
  75654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  75655. };
  75656. // Create blur H&V post-processes
  75657. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  75658. var _this = this;
  75659. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  75660. var engine = scene.getEngine();
  75661. 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);
  75662. 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);
  75663. blurX.onActivateObservable.add(function () {
  75664. var dw = blurX.width / engine.getRenderWidth();
  75665. blurX.kernel = _this[blurWidthKey] * dw;
  75666. });
  75667. blurY.onActivateObservable.add(function () {
  75668. var dw = blurY.height / engine.getRenderHeight();
  75669. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  75670. });
  75671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  75672. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  75673. this.blurHPostProcesses.push(blurX);
  75674. this.blurVPostProcesses.push(blurY);
  75675. };
  75676. // Create texture adder post-process
  75677. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  75678. var _this = this;
  75679. 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);
  75680. this.textureAdderPostProcess.onApply = function (effect) {
  75681. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  75682. effect.setTexture("lensSampler", _this.lensTexture);
  75683. effect.setFloat("exposure", _this.exposure);
  75684. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  75685. };
  75686. // Add to pipeline
  75687. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  75688. };
  75689. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  75690. var _this = this;
  75691. var geometryRenderer = scene.enableGeometryBufferRenderer();
  75692. geometryRenderer.enablePosition = true;
  75693. var geometry = geometryRenderer.getGBuffer();
  75694. // Base post-process
  75695. 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));
  75696. var depthValues = BABYLON.Vector2.Zero();
  75697. this.volumetricLightPostProcess.onApply = function (effect) {
  75698. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  75699. var generator = _this.sourceLight.getShadowGenerator();
  75700. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  75701. effect.setTexture("positionSampler", geometry.textures[2]);
  75702. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  75703. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  75704. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  75705. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  75706. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  75707. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  75708. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  75709. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  75710. effect.setVector2("depthValues", depthValues);
  75711. }
  75712. };
  75713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  75714. // Smooth
  75715. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75716. // Merge
  75717. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75718. this.volumetricLightMergePostProces.onApply = function (effect) {
  75719. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75720. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75721. };
  75722. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75723. };
  75724. // Create luminance
  75725. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75726. var _this = this;
  75727. // Create luminance
  75728. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75729. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75730. var offsets = [];
  75731. this.luminancePostProcess.onApply = function (effect) {
  75732. var sU = (1.0 / _this.luminancePostProcess.width);
  75733. var sV = (1.0 / _this.luminancePostProcess.height);
  75734. offsets[0] = -0.5 * sU;
  75735. offsets[1] = 0.5 * sV;
  75736. offsets[2] = 0.5 * sU;
  75737. offsets[3] = 0.5 * sV;
  75738. offsets[4] = -0.5 * sU;
  75739. offsets[5] = -0.5 * sV;
  75740. offsets[6] = 0.5 * sU;
  75741. offsets[7] = -0.5 * sV;
  75742. effect.setArray2("lumOffsets", offsets);
  75743. };
  75744. // Add to pipeline
  75745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75746. // Create down sample luminance
  75747. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75748. var size = Math.pow(3, i);
  75749. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75750. if (i === 0) {
  75751. defines += "#define FINAL_DOWN_SAMPLER";
  75752. }
  75753. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75754. this.luminanceDownSamplePostProcesses.push(postProcess);
  75755. }
  75756. // Create callbacks and add effects
  75757. var lastLuminance = this.luminancePostProcess;
  75758. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75759. var downSampleOffsets = new Array(18);
  75760. pp.onApply = function (effect) {
  75761. if (!lastLuminance) {
  75762. return;
  75763. }
  75764. var id = 0;
  75765. for (var x = -1; x < 2; x++) {
  75766. for (var y = -1; y < 2; y++) {
  75767. downSampleOffsets[id] = x / lastLuminance.width;
  75768. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75769. id += 2;
  75770. }
  75771. }
  75772. effect.setArray2("dsOffsets", downSampleOffsets);
  75773. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75774. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75775. lastLuminance = _this.luminancePostProcess;
  75776. }
  75777. else {
  75778. lastLuminance = pp;
  75779. }
  75780. };
  75781. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75782. pp.onAfterRender = function (effect) {
  75783. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75784. 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);
  75785. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75786. };
  75787. }
  75788. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75789. });
  75790. };
  75791. // Create HDR post-process
  75792. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75793. var _this = this;
  75794. 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);
  75795. var outputLiminance = 1;
  75796. var time = 0;
  75797. var lastTime = 0;
  75798. this.hdrPostProcess.onApply = function (effect) {
  75799. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75800. time += scene.getEngine().getDeltaTime();
  75801. if (outputLiminance < 0) {
  75802. outputLiminance = _this._hdrCurrentLuminance;
  75803. }
  75804. else {
  75805. var dt = (lastTime - time) / 1000.0;
  75806. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75807. outputLiminance += _this.hdrDecreaseRate * dt;
  75808. }
  75809. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75810. outputLiminance -= _this.hdrIncreaseRate * dt;
  75811. }
  75812. else {
  75813. outputLiminance = _this._hdrCurrentLuminance;
  75814. }
  75815. }
  75816. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75817. effect.setFloat("averageLuminance", outputLiminance);
  75818. lastTime = time;
  75819. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75820. };
  75821. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75822. };
  75823. // Create lens flare post-process
  75824. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75825. var _this = this;
  75826. 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);
  75827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75828. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75829. 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);
  75830. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75831. var resolution = new BABYLON.Vector2(0, 0);
  75832. // Lens flare
  75833. this.lensFlarePostProcess.onApply = function (effect) {
  75834. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75835. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75836. effect.setFloat("strength", _this.lensFlareStrength);
  75837. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75838. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75839. // Shift
  75840. resolution.x = _this.lensFlarePostProcess.width;
  75841. resolution.y = _this.lensFlarePostProcess.height;
  75842. effect.setVector2("resolution", resolution);
  75843. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75844. };
  75845. // Compose
  75846. 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);
  75847. 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);
  75848. this.lensFlareComposePostProcess.onApply = function (effect) {
  75849. if (!_this._scene.activeCamera) {
  75850. return;
  75851. }
  75852. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75853. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75854. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75855. // Lens start rotation matrix
  75856. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75857. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75858. 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));
  75859. camRot *= 4.0;
  75860. 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);
  75861. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75862. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75863. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75864. };
  75865. };
  75866. // Create depth-of-field post-process
  75867. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75868. var _this = this;
  75869. 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);
  75870. this.depthOfFieldPostProcess.onApply = function (effect) {
  75871. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75872. effect.setTexture("depthSampler", _this._getDepthTexture());
  75873. effect.setFloat("distance", _this.depthOfFieldDistance);
  75874. };
  75875. // Add to pipeline
  75876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75877. };
  75878. // Create motion blur post-process
  75879. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75880. var _this = this;
  75881. 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);
  75882. var motionScale = 0;
  75883. var prevViewProjection = BABYLON.Matrix.Identity();
  75884. var invViewProjection = BABYLON.Matrix.Identity();
  75885. var viewProjection = BABYLON.Matrix.Identity();
  75886. var screenSize = BABYLON.Vector2.Zero();
  75887. this.motionBlurPostProcess.onApply = function (effect) {
  75888. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75889. viewProjection.invertToRef(invViewProjection);
  75890. effect.setMatrix("inverseViewProjection", invViewProjection);
  75891. effect.setMatrix("prevViewProjection", prevViewProjection);
  75892. prevViewProjection = viewProjection;
  75893. screenSize.x = _this.motionBlurPostProcess.width;
  75894. screenSize.y = _this.motionBlurPostProcess.height;
  75895. effect.setVector2("screenSize", screenSize);
  75896. motionScale = scene.getEngine().getFps() / 60.0;
  75897. effect.setFloat("motionScale", motionScale);
  75898. effect.setFloat("motionStrength", _this.motionStrength);
  75899. effect.setTexture("depthSampler", _this._getDepthTexture());
  75900. };
  75901. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75902. };
  75903. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75904. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75905. var renderer = this._scene.enableGeometryBufferRenderer();
  75906. return renderer.getGBuffer().textures[0];
  75907. }
  75908. return this._scene.enableDepthRenderer().getDepthMap();
  75909. };
  75910. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75911. for (var i = 0; i < this._cameras.length; i++) {
  75912. var camera = this._cameras[i];
  75913. if (this.originalPostProcess) {
  75914. this.originalPostProcess.dispose(camera);
  75915. }
  75916. if (this.downSampleX4PostProcess) {
  75917. this.downSampleX4PostProcess.dispose(camera);
  75918. }
  75919. if (this.brightPassPostProcess) {
  75920. this.brightPassPostProcess.dispose(camera);
  75921. }
  75922. if (this.textureAdderPostProcess) {
  75923. this.textureAdderPostProcess.dispose(camera);
  75924. }
  75925. if (this.textureAdderFinalPostProcess) {
  75926. this.textureAdderFinalPostProcess.dispose(camera);
  75927. }
  75928. if (this.volumetricLightPostProcess) {
  75929. this.volumetricLightPostProcess.dispose(camera);
  75930. }
  75931. if (this.volumetricLightSmoothXPostProcess) {
  75932. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75933. }
  75934. if (this.volumetricLightSmoothYPostProcess) {
  75935. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75936. }
  75937. if (this.volumetricLightMergePostProces) {
  75938. this.volumetricLightMergePostProces.dispose(camera);
  75939. }
  75940. if (this.volumetricLightFinalPostProcess) {
  75941. this.volumetricLightFinalPostProcess.dispose(camera);
  75942. }
  75943. if (this.lensFlarePostProcess) {
  75944. this.lensFlarePostProcess.dispose(camera);
  75945. }
  75946. if (this.lensFlareComposePostProcess) {
  75947. this.lensFlareComposePostProcess.dispose(camera);
  75948. }
  75949. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75950. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75951. }
  75952. if (this.luminancePostProcess) {
  75953. this.luminancePostProcess.dispose(camera);
  75954. }
  75955. if (this.hdrPostProcess) {
  75956. this.hdrPostProcess.dispose(camera);
  75957. }
  75958. if (this.hdrFinalPostProcess) {
  75959. this.hdrFinalPostProcess.dispose(camera);
  75960. }
  75961. if (this.depthOfFieldPostProcess) {
  75962. this.depthOfFieldPostProcess.dispose(camera);
  75963. }
  75964. if (this.motionBlurPostProcess) {
  75965. this.motionBlurPostProcess.dispose(camera);
  75966. }
  75967. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75968. this.blurHPostProcesses[j].dispose(camera);
  75969. }
  75970. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75971. this.blurVPostProcesses[j].dispose(camera);
  75972. }
  75973. }
  75974. this.originalPostProcess = null;
  75975. this.downSampleX4PostProcess = null;
  75976. this.brightPassPostProcess = null;
  75977. this.textureAdderPostProcess = null;
  75978. this.textureAdderFinalPostProcess = null;
  75979. this.volumetricLightPostProcess = null;
  75980. this.volumetricLightSmoothXPostProcess = null;
  75981. this.volumetricLightSmoothYPostProcess = null;
  75982. this.volumetricLightMergePostProces = null;
  75983. this.volumetricLightFinalPostProcess = null;
  75984. this.lensFlarePostProcess = null;
  75985. this.lensFlareComposePostProcess = null;
  75986. this.luminancePostProcess = null;
  75987. this.hdrPostProcess = null;
  75988. this.hdrFinalPostProcess = null;
  75989. this.depthOfFieldPostProcess = null;
  75990. this.motionBlurPostProcess = null;
  75991. this.luminanceDownSamplePostProcesses = [];
  75992. this.blurHPostProcesses = [];
  75993. this.blurVPostProcesses = [];
  75994. };
  75995. /**
  75996. * Dispose of the pipeline and stop all post processes
  75997. */
  75998. StandardRenderingPipeline.prototype.dispose = function () {
  75999. this._disposePostProcesses();
  76000. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76001. _super.prototype.dispose.call(this);
  76002. };
  76003. /**
  76004. * Serialize the rendering pipeline (Used when exporting)
  76005. * @returns the serialized object
  76006. */
  76007. StandardRenderingPipeline.prototype.serialize = function () {
  76008. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76009. if (this.sourceLight) {
  76010. serializationObject.sourceLightId = this.sourceLight.id;
  76011. }
  76012. serializationObject.customType = "StandardRenderingPipeline";
  76013. return serializationObject;
  76014. };
  76015. /**
  76016. * Parse the serialized pipeline
  76017. * @param source Source pipeline.
  76018. * @param scene The scene to load the pipeline to.
  76019. * @param rootUrl The URL of the serialized pipeline.
  76020. * @returns An instantiated pipeline from the serialized object.
  76021. */
  76022. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76023. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76024. if (source.sourceLightId) {
  76025. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76026. }
  76027. return p;
  76028. };
  76029. // Luminance steps
  76030. StandardRenderingPipeline.LuminanceSteps = 6;
  76031. __decorate([
  76032. BABYLON.serialize()
  76033. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76034. __decorate([
  76035. BABYLON.serialize()
  76036. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76037. __decorate([
  76038. BABYLON.serialize()
  76039. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76040. __decorate([
  76041. BABYLON.serialize()
  76042. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76043. __decorate([
  76044. BABYLON.serializeAsTexture("lensTexture")
  76045. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76046. __decorate([
  76047. BABYLON.serialize()
  76048. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76049. __decorate([
  76050. BABYLON.serialize()
  76051. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76052. __decorate([
  76053. BABYLON.serialize()
  76054. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76055. __decorate([
  76056. BABYLON.serialize()
  76057. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76058. __decorate([
  76059. BABYLON.serialize()
  76060. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76061. __decorate([
  76062. BABYLON.serialize()
  76063. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76064. __decorate([
  76065. BABYLON.serializeAsTexture("lensColorTexture")
  76066. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76067. __decorate([
  76068. BABYLON.serialize()
  76069. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76070. __decorate([
  76071. BABYLON.serialize()
  76072. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76073. __decorate([
  76074. BABYLON.serialize()
  76075. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76076. __decorate([
  76077. BABYLON.serialize()
  76078. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76079. __decorate([
  76080. BABYLON.serializeAsTexture("lensStarTexture")
  76081. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  76082. __decorate([
  76083. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  76084. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  76085. __decorate([
  76086. BABYLON.serialize()
  76087. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  76088. __decorate([
  76089. BABYLON.serialize()
  76090. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  76091. __decorate([
  76092. BABYLON.serialize()
  76093. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  76094. __decorate([
  76095. BABYLON.serialize()
  76096. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  76097. __decorate([
  76098. BABYLON.serialize()
  76099. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  76100. __decorate([
  76101. BABYLON.serialize()
  76102. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  76103. __decorate([
  76104. BABYLON.serialize()
  76105. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  76106. __decorate([
  76107. BABYLON.serialize()
  76108. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  76109. __decorate([
  76110. BABYLON.serialize()
  76111. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  76112. __decorate([
  76113. BABYLON.serialize()
  76114. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  76115. __decorate([
  76116. BABYLON.serialize()
  76117. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  76118. __decorate([
  76119. BABYLON.serialize()
  76120. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  76121. return StandardRenderingPipeline;
  76122. }(BABYLON.PostProcessRenderPipeline));
  76123. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  76124. })(BABYLON || (BABYLON = {}));
  76125. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  76126. var BABYLON;
  76127. (function (BABYLON) {
  76128. var FxaaPostProcess = /** @class */ (function (_super) {
  76129. __extends(FxaaPostProcess, _super);
  76130. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76131. if (camera === void 0) { camera = null; }
  76132. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76133. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  76134. var defines = _this._getDefines();
  76135. _this.updateEffect(defines);
  76136. _this.onApplyObservable.add(function (effect) {
  76137. var texelSize = _this.texelSize;
  76138. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  76139. });
  76140. return _this;
  76141. }
  76142. FxaaPostProcess.prototype._getDefines = function () {
  76143. var engine = this.getEngine();
  76144. if (!engine) {
  76145. return null;
  76146. }
  76147. var glInfo = engine.getGlInfo();
  76148. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  76149. return "#define MALI 1\n";
  76150. }
  76151. return null;
  76152. };
  76153. return FxaaPostProcess;
  76154. }(BABYLON.PostProcess));
  76155. BABYLON.FxaaPostProcess = FxaaPostProcess;
  76156. })(BABYLON || (BABYLON = {}));
  76157. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  76158. var BABYLON;
  76159. (function (BABYLON) {
  76160. /**
  76161. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  76162. */
  76163. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  76164. __extends(ChromaticAberrationPostProcess, _super);
  76165. /**
  76166. * Creates a new instance ChromaticAberrationPostProcess
  76167. * @param name The name of the effect.
  76168. * @param screenWidth The width of the screen to apply the effect on.
  76169. * @param screenHeight The height of the screen to apply the effect on.
  76170. * @param options The required width/height ratio to downsize to before computing the render pass.
  76171. * @param camera The camera to apply the render pass to.
  76172. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76173. * @param engine The engine which the post process will be applied. (default: current engine)
  76174. * @param reusable If the post process can be reused on the same frame. (default: false)
  76175. * @param textureType Type of textures used when performing the post process. (default: 0)
  76176. * @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)
  76177. */
  76178. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76179. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76180. if (blockCompilation === void 0) { blockCompilation = false; }
  76181. 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;
  76182. /**
  76183. * The amount of seperation of rgb channels (default: 30)
  76184. */
  76185. _this.aberrationAmount = 30;
  76186. /**
  76187. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  76188. */
  76189. _this.radialIntensity = 0;
  76190. /**
  76191. * 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))
  76192. */
  76193. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  76194. /**
  76195. * 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))
  76196. */
  76197. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  76198. _this.onApplyObservable.add(function (effect) {
  76199. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  76200. effect.setFloat('screen_width', screenWidth);
  76201. effect.setFloat('screen_height', screenHeight);
  76202. effect.setFloat('radialIntensity', _this.radialIntensity);
  76203. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  76204. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  76205. });
  76206. return _this;
  76207. }
  76208. return ChromaticAberrationPostProcess;
  76209. }(BABYLON.PostProcess));
  76210. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  76211. })(BABYLON || (BABYLON = {}));
  76212. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  76213. var BABYLON;
  76214. (function (BABYLON) {
  76215. /**
  76216. * The GrainPostProcess adds noise to the image at mid luminance levels
  76217. */
  76218. var GrainPostProcess = /** @class */ (function (_super) {
  76219. __extends(GrainPostProcess, _super);
  76220. /**
  76221. * Creates a new instance of @see GrainPostProcess
  76222. * @param name The name of the effect.
  76223. * @param options The required width/height ratio to downsize to before computing the render pass.
  76224. * @param camera The camera to apply the render pass to.
  76225. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76226. * @param engine The engine which the post process will be applied. (default: current engine)
  76227. * @param reusable If the post process can be reused on the same frame. (default: false)
  76228. * @param textureType Type of textures used when performing the post process. (default: 0)
  76229. * @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)
  76230. */
  76231. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76232. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76233. if (blockCompilation === void 0) { blockCompilation = false; }
  76234. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76235. /**
  76236. * The intensity of the grain added (default: 30)
  76237. */
  76238. _this.intensity = 30;
  76239. /**
  76240. * If the grain should be randomized on every frame
  76241. */
  76242. _this.animated = false;
  76243. _this.onApplyObservable.add(function (effect) {
  76244. effect.setFloat('intensity', _this.intensity);
  76245. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  76246. });
  76247. return _this;
  76248. }
  76249. return GrainPostProcess;
  76250. }(BABYLON.PostProcess));
  76251. BABYLON.GrainPostProcess = GrainPostProcess;
  76252. })(BABYLON || (BABYLON = {}));
  76253. //# sourceMappingURL=babylon.grainPostProcess.js.map
  76254. var BABYLON;
  76255. (function (BABYLON) {
  76256. /**
  76257. * The SharpenPostProcess applies a sharpen kernel to every pixel
  76258. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76259. */
  76260. var SharpenPostProcess = /** @class */ (function (_super) {
  76261. __extends(SharpenPostProcess, _super);
  76262. /**
  76263. * Creates a new instance ConvolutionPostProcess
  76264. * @param name The name of the effect.
  76265. * @param options The required width/height ratio to downsize to before computing the render pass.
  76266. * @param camera The camera to apply the render pass to.
  76267. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76268. * @param engine The engine which the post process will be applied. (default: current engine)
  76269. * @param reusable If the post process can be reused on the same frame. (default: false)
  76270. * @param textureType Type of textures used when performing the post process. (default: 0)
  76271. * @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)
  76272. */
  76273. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76274. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76275. if (blockCompilation === void 0) { blockCompilation = false; }
  76276. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76277. /**
  76278. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  76279. */
  76280. _this.colorAmount = 1.0;
  76281. /**
  76282. * How much sharpness should be applied (default: 0.3)
  76283. */
  76284. _this.edgeAmount = 0.3;
  76285. _this.onApply = function (effect) {
  76286. effect.setFloat2("screenSize", _this.width, _this.height);
  76287. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  76288. };
  76289. return _this;
  76290. }
  76291. return SharpenPostProcess;
  76292. }(BABYLON.PostProcess));
  76293. BABYLON.SharpenPostProcess = SharpenPostProcess;
  76294. })(BABYLON || (BABYLON = {}));
  76295. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  76296. var BABYLON;
  76297. (function (BABYLON) {
  76298. /**
  76299. * The Blur Post Process which blurs an image based on a kernel and direction.
  76300. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  76301. */
  76302. var BlurPostProcess = /** @class */ (function (_super) {
  76303. __extends(BlurPostProcess, _super);
  76304. /**
  76305. * Creates a new instance BlurPostProcess
  76306. * @param name The name of the effect.
  76307. * @param direction The direction in which to blur the image.
  76308. * @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.
  76309. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76310. * @param camera The camera to apply the render pass to.
  76311. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76312. * @param engine The engine which the post process will be applied. (default: current engine)
  76313. * @param reusable If the post process can be reused on the same frame. (default: false)
  76314. * @param textureType Type of textures used when performing the post process. (default: 0)
  76315. * @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)
  76316. */
  76317. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  76318. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76319. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76320. if (defines === void 0) { defines = ""; }
  76321. if (blockCompilation === void 0) { blockCompilation = false; }
  76322. 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;
  76323. _this.direction = direction;
  76324. _this.blockCompilation = blockCompilation;
  76325. _this._packedFloat = false;
  76326. _this._staticDefines = "";
  76327. _this._staticDefines = defines;
  76328. _this.onApplyObservable.add(function (effect) {
  76329. if (_this._outputTexture) {
  76330. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  76331. }
  76332. else {
  76333. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  76334. }
  76335. });
  76336. _this.kernel = kernel;
  76337. return _this;
  76338. }
  76339. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  76340. /**
  76341. * Gets the length in pixels of the blur sample region
  76342. */
  76343. get: function () {
  76344. return this._idealKernel;
  76345. },
  76346. /**
  76347. * Sets the length in pixels of the blur sample region
  76348. */
  76349. set: function (v) {
  76350. if (this._idealKernel === v) {
  76351. return;
  76352. }
  76353. v = Math.max(v, 1);
  76354. this._idealKernel = v;
  76355. this._kernel = this._nearestBestKernel(v);
  76356. if (!this.blockCompilation) {
  76357. this._updateParameters();
  76358. }
  76359. },
  76360. enumerable: true,
  76361. configurable: true
  76362. });
  76363. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  76364. /**
  76365. * Gets wether or not the blur is unpacking/repacking floats
  76366. */
  76367. get: function () {
  76368. return this._packedFloat;
  76369. },
  76370. /**
  76371. * Sets wether or not the blur needs to unpack/repack floats
  76372. */
  76373. set: function (v) {
  76374. if (this._packedFloat === v) {
  76375. return;
  76376. }
  76377. this._packedFloat = v;
  76378. if (!this.blockCompilation) {
  76379. this._updateParameters();
  76380. }
  76381. },
  76382. enumerable: true,
  76383. configurable: true
  76384. });
  76385. /**
  76386. * Updates the effect with the current post process compile time values and recompiles the shader.
  76387. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76388. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76389. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76390. * @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
  76391. * @param onCompiled Called when the shader has been compiled.
  76392. * @param onError Called if there is an error when compiling a shader.
  76393. */
  76394. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76395. if (defines === void 0) { defines = null; }
  76396. if (uniforms === void 0) { uniforms = null; }
  76397. if (samplers === void 0) { samplers = null; }
  76398. this._updateParameters(onCompiled, onError);
  76399. };
  76400. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  76401. // Generate sampling offsets and weights
  76402. var N = this._kernel;
  76403. var centerIndex = (N - 1) / 2;
  76404. // Generate Gaussian sampling weights over kernel
  76405. var offsets = [];
  76406. var weights = [];
  76407. var totalWeight = 0;
  76408. for (var i = 0; i < N; i++) {
  76409. var u = i / (N - 1);
  76410. var w = this._gaussianWeight(u * 2.0 - 1);
  76411. offsets[i] = (i - centerIndex);
  76412. weights[i] = w;
  76413. totalWeight += w;
  76414. }
  76415. // Normalize weights
  76416. for (var i = 0; i < weights.length; i++) {
  76417. weights[i] /= totalWeight;
  76418. }
  76419. // Optimize: combine samples to take advantage of hardware linear sampling
  76420. // Walk from left to center, combining pairs (symmetrically)
  76421. var linearSamplingWeights = [];
  76422. var linearSamplingOffsets = [];
  76423. var linearSamplingMap = [];
  76424. for (var i = 0; i <= centerIndex; i += 2) {
  76425. var j = Math.min(i + 1, Math.floor(centerIndex));
  76426. var singleCenterSample = i === j;
  76427. if (singleCenterSample) {
  76428. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76429. }
  76430. else {
  76431. var sharedCell = j === centerIndex;
  76432. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  76433. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  76434. if (offsetLinear === 0) {
  76435. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76436. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  76437. }
  76438. else {
  76439. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  76440. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  76441. }
  76442. }
  76443. }
  76444. for (var i = 0; i < linearSamplingMap.length; i++) {
  76445. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  76446. linearSamplingWeights[i] = linearSamplingMap[i].w;
  76447. }
  76448. // Replace with optimized
  76449. offsets = linearSamplingOffsets;
  76450. weights = linearSamplingWeights;
  76451. // Generate shaders
  76452. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  76453. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  76454. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  76455. var defines = "";
  76456. defines += this._staticDefines;
  76457. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  76458. if (this._staticDefines.indexOf("DOF") != -1) {
  76459. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  76460. varyingCount--;
  76461. }
  76462. for (var i = 0; i < varyingCount; i++) {
  76463. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  76464. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  76465. }
  76466. var depCount = 0;
  76467. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  76468. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  76469. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  76470. depCount++;
  76471. }
  76472. if (this.packedFloat) {
  76473. defines += "#define PACKEDFLOAT 1";
  76474. }
  76475. this.blockCompilation = false;
  76476. _super.prototype.updateEffect.call(this, defines, null, null, {
  76477. varyingCount: varyingCount,
  76478. depCount: depCount
  76479. }, onCompiled, onError);
  76480. };
  76481. /**
  76482. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  76483. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  76484. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  76485. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  76486. * The gaps between physical kernels are compensated for in the weighting of the samples
  76487. * @param idealKernel Ideal blur kernel.
  76488. * @return Nearest best kernel.
  76489. */
  76490. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  76491. var v = Math.round(idealKernel);
  76492. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  76493. var k = _a[_i];
  76494. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  76495. return Math.max(k, 3);
  76496. }
  76497. }
  76498. return Math.max(v, 3);
  76499. };
  76500. /**
  76501. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  76502. * @param x The point on the Gaussian distribution to sample.
  76503. * @return the value of the Gaussian function at x.
  76504. */
  76505. BlurPostProcess.prototype._gaussianWeight = function (x) {
  76506. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  76507. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  76508. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  76509. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  76510. // truncated at around 1.3% of peak strength.
  76511. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  76512. var sigma = (1 / 3);
  76513. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  76514. var exponent = -((x * x) / (2.0 * sigma * sigma));
  76515. var weight = (1.0 / denominator) * Math.exp(exponent);
  76516. return weight;
  76517. };
  76518. /**
  76519. * Generates a string that can be used as a floating point number in GLSL.
  76520. * @param x Value to print.
  76521. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  76522. * @return GLSL float string.
  76523. */
  76524. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  76525. if (decimalFigures === void 0) { decimalFigures = 8; }
  76526. return x.toFixed(decimalFigures).replace(/0+$/, '');
  76527. };
  76528. return BlurPostProcess;
  76529. }(BABYLON.PostProcess));
  76530. BABYLON.BlurPostProcess = BlurPostProcess;
  76531. })(BABYLON || (BABYLON = {}));
  76532. //# sourceMappingURL=babylon.blurPostProcess.js.map
  76533. var BABYLON;
  76534. (function (BABYLON) {
  76535. /**
  76536. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  76537. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  76538. * based on samples that have a large difference in distance than the center pixel.
  76539. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76540. */
  76541. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  76542. __extends(DepthOfFieldBlurPostProcess, _super);
  76543. /**
  76544. * Creates a new instance CircleOfConfusionPostProcess
  76545. * @param name The name of the effect.
  76546. * @param scene The scene the effect belongs to.
  76547. * @param direction The direction the blur should be applied.
  76548. * @param kernel The size of the kernel used to blur.
  76549. * @param options The required width/height ratio to downsize to before computing the render pass.
  76550. * @param camera The camera to apply the render pass to.
  76551. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  76552. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  76553. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76554. * @param engine The engine which the post process will be applied. (default: current engine)
  76555. * @param reusable If the post process can be reused on the same frame. (default: false)
  76556. * @param textureType Type of textures used when performing the post process. (default: 0)
  76557. * @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)
  76558. */
  76559. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  76560. if (imageToBlur === void 0) { imageToBlur = null; }
  76561. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76562. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76563. if (blockCompilation === void 0) { blockCompilation = false; }
  76564. 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;
  76565. _this.direction = direction;
  76566. _this.onApplyObservable.add(function (effect) {
  76567. if (imageToBlur != null) {
  76568. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  76569. }
  76570. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76571. if (scene.activeCamera) {
  76572. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76573. }
  76574. });
  76575. return _this;
  76576. }
  76577. return DepthOfFieldBlurPostProcess;
  76578. }(BABYLON.BlurPostProcess));
  76579. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  76580. })(BABYLON || (BABYLON = {}));
  76581. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  76582. var BABYLON;
  76583. (function (BABYLON) {
  76584. /**
  76585. * Options to be set when merging outputs from the default pipeline.
  76586. */
  76587. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  76588. function DepthOfFieldMergePostProcessOptions() {
  76589. }
  76590. return DepthOfFieldMergePostProcessOptions;
  76591. }());
  76592. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  76593. /**
  76594. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76595. */
  76596. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  76597. __extends(DepthOfFieldMergePostProcess, _super);
  76598. /**
  76599. * Creates a new instance of DepthOfFieldMergePostProcess
  76600. * @param name The name of the effect.
  76601. * @param originalFromInput Post process which's input will be used for the merge.
  76602. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  76603. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  76604. * @param options The required width/height ratio to downsize to before computing the render pass.
  76605. * @param camera The camera to apply the render pass to.
  76606. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76607. * @param engine The engine which the post process will be applied. (default: current engine)
  76608. * @param reusable If the post process can be reused on the same frame. (default: false)
  76609. * @param textureType Type of textures used when performing the post process. (default: 0)
  76610. * @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)
  76611. */
  76612. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76613. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76614. if (blockCompilation === void 0) { blockCompilation = false; }
  76615. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76616. _this.blurSteps = blurSteps;
  76617. _this.onApplyObservable.add(function (effect) {
  76618. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76619. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76620. blurSteps.forEach(function (step, index) {
  76621. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  76622. });
  76623. });
  76624. if (!blockCompilation) {
  76625. _this.updateEffect();
  76626. }
  76627. return _this;
  76628. }
  76629. /**
  76630. * Updates the effect with the current post process compile time values and recompiles the shader.
  76631. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76632. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76633. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76634. * @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
  76635. * @param onCompiled Called when the shader has been compiled.
  76636. * @param onError Called if there is an error when compiling a shader.
  76637. */
  76638. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76639. if (defines === void 0) { defines = null; }
  76640. if (uniforms === void 0) { uniforms = null; }
  76641. if (samplers === void 0) { samplers = null; }
  76642. if (!defines) {
  76643. defines = "";
  76644. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  76645. }
  76646. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  76647. };
  76648. return DepthOfFieldMergePostProcess;
  76649. }(BABYLON.PostProcess));
  76650. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  76651. })(BABYLON || (BABYLON = {}));
  76652. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  76653. var BABYLON;
  76654. (function (BABYLON) {
  76655. /**
  76656. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  76657. */
  76658. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  76659. __extends(CircleOfConfusionPostProcess, _super);
  76660. /**
  76661. * Creates a new instance CircleOfConfusionPostProcess
  76662. * @param name The name of the effect.
  76663. * @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.
  76664. * @param options The required width/height ratio to downsize to before computing the render pass.
  76665. * @param camera The camera to apply the render pass to.
  76666. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76667. * @param engine The engine which the post process will be applied. (default: current engine)
  76668. * @param reusable If the post process can be reused on the same frame. (default: false)
  76669. * @param textureType Type of textures used when performing the post process. (default: 0)
  76670. * @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)
  76671. */
  76672. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76673. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76674. if (blockCompilation === void 0) { blockCompilation = false; }
  76675. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76676. /**
  76677. * 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.
  76678. */
  76679. _this.lensSize = 50;
  76680. /**
  76681. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76682. */
  76683. _this.fStop = 1.4;
  76684. /**
  76685. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76686. */
  76687. _this.focusDistance = 2000;
  76688. /**
  76689. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  76690. */
  76691. _this.focalLength = 50;
  76692. _this._depthTexture = null;
  76693. _this._depthTexture = depthTexture;
  76694. _this.onApplyObservable.add(function (effect) {
  76695. if (!_this._depthTexture) {
  76696. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  76697. return;
  76698. }
  76699. effect.setTexture("depthSampler", _this._depthTexture);
  76700. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  76701. var aperture = _this.lensSize / _this.fStop;
  76702. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  76703. effect.setFloat('focusDistance', _this.focusDistance);
  76704. effect.setFloat('cocPrecalculation', cocPrecalculation);
  76705. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  76706. });
  76707. return _this;
  76708. }
  76709. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  76710. /**
  76711. * 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.
  76712. */
  76713. set: function (value) {
  76714. this._depthTexture = value;
  76715. },
  76716. enumerable: true,
  76717. configurable: true
  76718. });
  76719. return CircleOfConfusionPostProcess;
  76720. }(BABYLON.PostProcess));
  76721. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76722. })(BABYLON || (BABYLON = {}));
  76723. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76724. var BABYLON;
  76725. (function (BABYLON) {
  76726. /**
  76727. * Specifies the level of max blur that should be applied when using the depth of field effect
  76728. */
  76729. var DepthOfFieldEffectBlurLevel;
  76730. (function (DepthOfFieldEffectBlurLevel) {
  76731. /**
  76732. * Subtle blur
  76733. */
  76734. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76735. /**
  76736. * Medium blur
  76737. */
  76738. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76739. /**
  76740. * Large blur
  76741. */
  76742. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76743. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76744. ;
  76745. /**
  76746. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76747. */
  76748. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76749. __extends(DepthOfFieldEffect, _super);
  76750. /**
  76751. * Creates a new instance DepthOfFieldEffect
  76752. * @param scene The scene the effect belongs to.
  76753. * @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.
  76754. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76755. * @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)
  76756. */
  76757. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76758. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76759. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76760. if (blockCompilation === void 0) { blockCompilation = false; }
  76761. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76762. return _this._effects;
  76763. }, true) || this;
  76764. /**
  76765. * Internal post processes in depth of field effect
  76766. */
  76767. _this._effects = [];
  76768. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76769. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76770. // 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)
  76771. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76772. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76773. _this._depthOfFieldBlurY = [];
  76774. _this._depthOfFieldBlurX = [];
  76775. var blurCount = 1;
  76776. var kernelSize = 15;
  76777. switch (blurLevel) {
  76778. case DepthOfFieldEffectBlurLevel.High: {
  76779. blurCount = 3;
  76780. kernelSize = 51;
  76781. break;
  76782. }
  76783. case DepthOfFieldEffectBlurLevel.Medium: {
  76784. blurCount = 2;
  76785. kernelSize = 31;
  76786. break;
  76787. }
  76788. default: {
  76789. kernelSize = 15;
  76790. blurCount = 1;
  76791. break;
  76792. }
  76793. }
  76794. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76795. var ratio = 1.0;
  76796. for (var i = 0; i < blurCount; i++) {
  76797. 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);
  76798. blurY.autoClear = false;
  76799. ratio = 0.75 / Math.pow(2, i);
  76800. 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);
  76801. blurX.autoClear = false;
  76802. _this._depthOfFieldBlurY.push(blurY);
  76803. _this._depthOfFieldBlurX.push(blurX);
  76804. }
  76805. // Set all post processes on the effect.
  76806. _this._effects = [_this._circleOfConfusion];
  76807. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76808. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76809. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76810. }
  76811. // Merge blurred images with original image based on circleOfConfusion
  76812. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76813. _this._dofMerge.autoClear = false;
  76814. _this._effects.push(_this._dofMerge);
  76815. return _this;
  76816. }
  76817. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76818. get: function () {
  76819. return this._circleOfConfusion.focalLength;
  76820. },
  76821. /**
  76822. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76823. */
  76824. set: function (value) {
  76825. this._circleOfConfusion.focalLength = value;
  76826. },
  76827. enumerable: true,
  76828. configurable: true
  76829. });
  76830. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76831. get: function () {
  76832. return this._circleOfConfusion.fStop;
  76833. },
  76834. /**
  76835. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76836. */
  76837. set: function (value) {
  76838. this._circleOfConfusion.fStop = value;
  76839. },
  76840. enumerable: true,
  76841. configurable: true
  76842. });
  76843. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76844. get: function () {
  76845. return this._circleOfConfusion.focusDistance;
  76846. },
  76847. /**
  76848. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76849. */
  76850. set: function (value) {
  76851. this._circleOfConfusion.focusDistance = value;
  76852. },
  76853. enumerable: true,
  76854. configurable: true
  76855. });
  76856. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76857. get: function () {
  76858. return this._circleOfConfusion.lensSize;
  76859. },
  76860. /**
  76861. * 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.
  76862. */
  76863. set: function (value) {
  76864. this._circleOfConfusion.lensSize = value;
  76865. },
  76866. enumerable: true,
  76867. configurable: true
  76868. });
  76869. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76870. /**
  76871. * 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.
  76872. */
  76873. set: function (value) {
  76874. this._circleOfConfusion.depthTexture = value;
  76875. },
  76876. enumerable: true,
  76877. configurable: true
  76878. });
  76879. /**
  76880. * Disposes each of the internal effects for a given camera.
  76881. * @param camera The camera to dispose the effect on.
  76882. */
  76883. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76884. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76885. this._effects[effectIndex].dispose(camera);
  76886. }
  76887. };
  76888. /**
  76889. * Internal
  76890. */
  76891. DepthOfFieldEffect.prototype._updateEffects = function () {
  76892. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76893. this._effects[effectIndex].updateEffect();
  76894. }
  76895. };
  76896. /**
  76897. * Internal
  76898. * @returns if all the contained post processes are ready.
  76899. */
  76900. DepthOfFieldEffect.prototype._isReady = function () {
  76901. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76902. if (!this._effects[effectIndex].isReady()) {
  76903. return false;
  76904. }
  76905. }
  76906. return true;
  76907. };
  76908. return DepthOfFieldEffect;
  76909. }(BABYLON.PostProcessRenderEffect));
  76910. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76911. })(BABYLON || (BABYLON = {}));
  76912. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76913. var BABYLON;
  76914. (function (BABYLON) {
  76915. /**
  76916. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76917. */
  76918. var BloomMergePostProcess = /** @class */ (function (_super) {
  76919. __extends(BloomMergePostProcess, _super);
  76920. /**
  76921. * Creates a new instance of @see BloomMergePostProcess
  76922. * @param name The name of the effect.
  76923. * @param originalFromInput Post process which's input will be used for the merge.
  76924. * @param blurred Blurred highlights post process which's output will be used.
  76925. * @param weight Weight of the bloom to be added to the original input.
  76926. * @param options The required width/height ratio to downsize to before computing the render pass.
  76927. * @param camera The camera to apply the render pass to.
  76928. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76929. * @param engine The engine which the post process will be applied. (default: current engine)
  76930. * @param reusable If the post process can be reused on the same frame. (default: false)
  76931. * @param textureType Type of textures used when performing the post process. (default: 0)
  76932. * @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)
  76933. */
  76934. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76935. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76936. if (blockCompilation === void 0) { blockCompilation = false; }
  76937. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76938. _this.weight = weight;
  76939. _this.onApplyObservable.add(function (effect) {
  76940. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76941. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76942. effect.setFloat("bloomWeight", _this.weight);
  76943. });
  76944. if (!blockCompilation) {
  76945. _this.updateEffect();
  76946. }
  76947. return _this;
  76948. }
  76949. return BloomMergePostProcess;
  76950. }(BABYLON.PostProcess));
  76951. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76952. })(BABYLON || (BABYLON = {}));
  76953. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76954. var BABYLON;
  76955. (function (BABYLON) {
  76956. /**
  76957. * 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.
  76958. */
  76959. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76960. __extends(ExtractHighlightsPostProcess, _super);
  76961. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76962. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76963. if (blockCompilation === void 0) { blockCompilation = false; }
  76964. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76965. /**
  76966. * The luminance threshold, pixels below this value will be set to black.
  76967. */
  76968. _this.threshold = 0.9;
  76969. /**
  76970. * Internal
  76971. */
  76972. _this._exposure = 1;
  76973. /**
  76974. * Post process which has the input texture to be used when performing highlight extraction
  76975. */
  76976. _this._inputPostProcess = null;
  76977. _this.onApplyObservable.add(function (effect) {
  76978. if (_this._inputPostProcess) {
  76979. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76980. }
  76981. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76982. effect.setFloat('exposure', _this._exposure);
  76983. });
  76984. return _this;
  76985. }
  76986. return ExtractHighlightsPostProcess;
  76987. }(BABYLON.PostProcess));
  76988. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76989. })(BABYLON || (BABYLON = {}));
  76990. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76991. var BABYLON;
  76992. (function (BABYLON) {
  76993. /**
  76994. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76995. */
  76996. var BloomEffect = /** @class */ (function (_super) {
  76997. __extends(BloomEffect, _super);
  76998. /**
  76999. * Creates a new instance of @see BloomEffect
  77000. * @param scene The scene the effect belongs to.
  77001. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77002. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77003. * @param bloomWeight The the strength of bloom.
  77004. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77005. * @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)
  77006. */
  77007. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77008. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77009. if (blockCompilation === void 0) { blockCompilation = false; }
  77010. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77011. return _this._effects;
  77012. }, true) || this;
  77013. _this.bloomScale = bloomScale;
  77014. /**
  77015. * Internal
  77016. */
  77017. _this._effects = [];
  77018. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77019. _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);
  77020. _this._blurX.alwaysForcePOT = true;
  77021. _this._blurX.autoClear = false;
  77022. _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);
  77023. _this._blurY.alwaysForcePOT = true;
  77024. _this._blurY.autoClear = false;
  77025. _this.kernel = bloomKernel;
  77026. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77027. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77028. _this._merge.autoClear = false;
  77029. _this._effects.push(_this._merge);
  77030. return _this;
  77031. }
  77032. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77033. /**
  77034. * The luminance threshold to find bright areas of the image to bloom.
  77035. */
  77036. get: function () {
  77037. return this._downscale.threshold;
  77038. },
  77039. set: function (value) {
  77040. this._downscale.threshold = value;
  77041. },
  77042. enumerable: true,
  77043. configurable: true
  77044. });
  77045. Object.defineProperty(BloomEffect.prototype, "weight", {
  77046. /**
  77047. * The strength of the bloom.
  77048. */
  77049. get: function () {
  77050. return this._merge.weight;
  77051. },
  77052. set: function (value) {
  77053. this._merge.weight = value;
  77054. },
  77055. enumerable: true,
  77056. configurable: true
  77057. });
  77058. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77059. /**
  77060. * Specifies the size of the bloom blur kernel, relative to the final output size
  77061. */
  77062. get: function () {
  77063. return this._blurX.kernel / this.bloomScale;
  77064. },
  77065. set: function (value) {
  77066. this._blurX.kernel = value * this.bloomScale;
  77067. this._blurY.kernel = value * this.bloomScale;
  77068. },
  77069. enumerable: true,
  77070. configurable: true
  77071. });
  77072. /**
  77073. * Disposes each of the internal effects for a given camera.
  77074. * @param camera The camera to dispose the effect on.
  77075. */
  77076. BloomEffect.prototype.disposeEffects = function (camera) {
  77077. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77078. this._effects[effectIndex].dispose(camera);
  77079. }
  77080. };
  77081. /**
  77082. * Internal
  77083. */
  77084. BloomEffect.prototype._updateEffects = function () {
  77085. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77086. this._effects[effectIndex].updateEffect();
  77087. }
  77088. };
  77089. /**
  77090. * Internal
  77091. * @returns if all the contained post processes are ready.
  77092. */
  77093. BloomEffect.prototype._isReady = function () {
  77094. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77095. if (!this._effects[effectIndex].isReady()) {
  77096. return false;
  77097. }
  77098. }
  77099. return true;
  77100. };
  77101. return BloomEffect;
  77102. }(BABYLON.PostProcessRenderEffect));
  77103. BABYLON.BloomEffect = BloomEffect;
  77104. })(BABYLON || (BABYLON = {}));
  77105. //# sourceMappingURL=babylon.bloomEffect.js.map
  77106. var BABYLON;
  77107. (function (BABYLON) {
  77108. /**
  77109. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  77110. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  77111. */
  77112. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  77113. __extends(DefaultRenderingPipeline, _super);
  77114. /**
  77115. * @constructor
  77116. * @param {string} name - The rendering pipeline name (default: "")
  77117. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  77118. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  77119. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  77120. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  77121. */
  77122. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  77123. if (name === void 0) { name = ""; }
  77124. if (hdr === void 0) { hdr = true; }
  77125. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77126. if (automaticBuild === void 0) { automaticBuild = true; }
  77127. var _this = _super.call(this, scene.getEngine(), name) || this;
  77128. _this._camerasToBeAttached = [];
  77129. /**
  77130. * ID of the sharpen post process,
  77131. */
  77132. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  77133. /**
  77134. * ID of the image processing post process;
  77135. */
  77136. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  77137. /**
  77138. * ID of the Fast Approximate Anti-Aliasing post process;
  77139. */
  77140. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  77141. /**
  77142. * ID of the chromatic aberration post process,
  77143. */
  77144. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  77145. /**
  77146. * ID of the grain post process
  77147. */
  77148. _this.GrainPostProcessId = "GrainPostProcessEffect";
  77149. /**
  77150. * Glow post process which adds a glow to emmisive areas of the image
  77151. */
  77152. _this._glowLayer = null;
  77153. /**
  77154. * Animations which can be used to tweak settings over a period of time
  77155. */
  77156. _this.animations = [];
  77157. _this._imageProcessingConfigurationObserver = null;
  77158. // Values
  77159. _this._sharpenEnabled = false;
  77160. _this._bloomEnabled = false;
  77161. _this._depthOfFieldEnabled = false;
  77162. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  77163. _this._fxaaEnabled = false;
  77164. _this._imageProcessingEnabled = true;
  77165. _this._bloomScale = 0.5;
  77166. _this._chromaticAberrationEnabled = false;
  77167. _this._grainEnabled = false;
  77168. _this._buildAllowed = true;
  77169. _this._resizeObserver = null;
  77170. _this._hardwareScaleLevel = 1.0;
  77171. _this._bloomKernel = 64;
  77172. /**
  77173. * Specifies the weight of the bloom in the final rendering
  77174. */
  77175. _this._bloomWeight = 0.15;
  77176. /**
  77177. * Specifies the luma threshold for the area that will be blurred by the bloom
  77178. */
  77179. _this._bloomThreshold = 0.9;
  77180. _this._samples = 1;
  77181. _this._hasCleared = false;
  77182. _this._prevPostProcess = null;
  77183. _this._prevPrevPostProcess = null;
  77184. _this._cameras = cameras || scene.cameras;
  77185. _this._camerasToBeAttached = _this._cameras.slice();
  77186. _this._buildAllowed = automaticBuild;
  77187. // Initialize
  77188. _this._scene = scene;
  77189. var caps = _this._scene.getEngine().getCaps();
  77190. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  77191. // Misc
  77192. if (_this._hdr) {
  77193. if (caps.textureHalfFloatRender) {
  77194. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77195. }
  77196. else if (caps.textureFloatRender) {
  77197. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77198. }
  77199. }
  77200. else {
  77201. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77202. }
  77203. // Attach
  77204. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77205. var engine = _this._scene.getEngine();
  77206. // Create post processes before hand so they can be modified before enabled.
  77207. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  77208. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77209. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  77210. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  77211. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  77212. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77213. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  77214. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77215. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  77216. _this._resizeObserver = engine.onResizeObservable.add(function () {
  77217. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  77218. _this.bloomKernel = _this.bloomKernel;
  77219. });
  77220. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  77221. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  77222. });
  77223. _this._buildPipeline();
  77224. return _this;
  77225. }
  77226. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  77227. get: function () {
  77228. return this._sharpenEnabled;
  77229. },
  77230. /**
  77231. * Enable or disable the sharpen process from the pipeline
  77232. */
  77233. set: function (enabled) {
  77234. if (this._sharpenEnabled === enabled) {
  77235. return;
  77236. }
  77237. this._sharpenEnabled = enabled;
  77238. this._buildPipeline();
  77239. },
  77240. enumerable: true,
  77241. configurable: true
  77242. });
  77243. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  77244. /**
  77245. * Specifies the size of the bloom blur kernel, relative to the final output size
  77246. */
  77247. get: function () {
  77248. return this._bloomKernel;
  77249. },
  77250. set: function (value) {
  77251. this._bloomKernel = value;
  77252. this.bloom.kernel = value / this._hardwareScaleLevel;
  77253. },
  77254. enumerable: true,
  77255. configurable: true
  77256. });
  77257. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  77258. get: function () {
  77259. return this._bloomWeight;
  77260. },
  77261. /**
  77262. * The strength of the bloom.
  77263. */
  77264. set: function (value) {
  77265. if (this._bloomWeight === value) {
  77266. return;
  77267. }
  77268. this.bloom.weight = value;
  77269. this._bloomWeight = value;
  77270. },
  77271. enumerable: true,
  77272. configurable: true
  77273. });
  77274. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  77275. get: function () {
  77276. return this._bloomThreshold;
  77277. },
  77278. /**
  77279. * The strength of the bloom.
  77280. */
  77281. set: function (value) {
  77282. if (this._bloomThreshold === value) {
  77283. return;
  77284. }
  77285. this.bloom.threshold = value;
  77286. this._bloomThreshold = value;
  77287. },
  77288. enumerable: true,
  77289. configurable: true
  77290. });
  77291. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  77292. get: function () {
  77293. return this._bloomScale;
  77294. },
  77295. /**
  77296. * The scale of the bloom, lower value will provide better performance.
  77297. */
  77298. set: function (value) {
  77299. if (this._bloomScale === value) {
  77300. return;
  77301. }
  77302. this._bloomScale = value;
  77303. // recreate bloom and dispose old as this setting is not dynamic
  77304. this._rebuildBloom();
  77305. this._buildPipeline();
  77306. },
  77307. enumerable: true,
  77308. configurable: true
  77309. });
  77310. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  77311. get: function () {
  77312. return this._bloomEnabled;
  77313. },
  77314. /**
  77315. * Enable or disable the bloom from the pipeline
  77316. */
  77317. set: function (enabled) {
  77318. if (this._bloomEnabled === enabled) {
  77319. return;
  77320. }
  77321. this._bloomEnabled = enabled;
  77322. this._buildPipeline();
  77323. },
  77324. enumerable: true,
  77325. configurable: true
  77326. });
  77327. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  77328. // recreate bloom and dispose old as this setting is not dynamic
  77329. var oldBloom = this.bloom;
  77330. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  77331. this.bloom.threshold = oldBloom.threshold;
  77332. for (var i = 0; i < this._cameras.length; i++) {
  77333. oldBloom.disposeEffects(this._cameras[i]);
  77334. }
  77335. };
  77336. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  77337. /**
  77338. * If the depth of field is enabled.
  77339. */
  77340. get: function () {
  77341. return this._depthOfFieldEnabled;
  77342. },
  77343. set: function (enabled) {
  77344. if (this._depthOfFieldEnabled === enabled) {
  77345. return;
  77346. }
  77347. this._depthOfFieldEnabled = enabled;
  77348. this._buildPipeline();
  77349. },
  77350. enumerable: true,
  77351. configurable: true
  77352. });
  77353. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  77354. /**
  77355. * Blur level of the depth of field effect. (Higher blur will effect performance)
  77356. */
  77357. get: function () {
  77358. return this._depthOfFieldBlurLevel;
  77359. },
  77360. set: function (value) {
  77361. if (this._depthOfFieldBlurLevel === value) {
  77362. return;
  77363. }
  77364. this._depthOfFieldBlurLevel = value;
  77365. // recreate dof and dispose old as this setting is not dynamic
  77366. var oldDof = this.depthOfField;
  77367. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  77368. this.depthOfField.focalLength = oldDof.focalLength;
  77369. this.depthOfField.focusDistance = oldDof.focusDistance;
  77370. this.depthOfField.fStop = oldDof.fStop;
  77371. this.depthOfField.lensSize = oldDof.lensSize;
  77372. for (var i = 0; i < this._cameras.length; i++) {
  77373. oldDof.disposeEffects(this._cameras[i]);
  77374. }
  77375. this._buildPipeline();
  77376. },
  77377. enumerable: true,
  77378. configurable: true
  77379. });
  77380. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  77381. get: function () {
  77382. return this._fxaaEnabled;
  77383. },
  77384. /**
  77385. * If the anti aliasing is enabled.
  77386. */
  77387. set: function (enabled) {
  77388. if (this._fxaaEnabled === enabled) {
  77389. return;
  77390. }
  77391. this._fxaaEnabled = enabled;
  77392. this._buildPipeline();
  77393. },
  77394. enumerable: true,
  77395. configurable: true
  77396. });
  77397. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  77398. get: function () {
  77399. return this._samples;
  77400. },
  77401. /**
  77402. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  77403. */
  77404. set: function (sampleCount) {
  77405. if (this._samples === sampleCount) {
  77406. return;
  77407. }
  77408. this._samples = sampleCount;
  77409. this._buildPipeline();
  77410. },
  77411. enumerable: true,
  77412. configurable: true
  77413. });
  77414. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  77415. get: function () {
  77416. return this._imageProcessingEnabled;
  77417. },
  77418. /**
  77419. * If image processing is enabled.
  77420. */
  77421. set: function (enabled) {
  77422. if (this._imageProcessingEnabled === enabled) {
  77423. return;
  77424. }
  77425. this._imageProcessingEnabled = enabled;
  77426. this._buildPipeline();
  77427. },
  77428. enumerable: true,
  77429. configurable: true
  77430. });
  77431. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  77432. get: function () {
  77433. return this._glowLayer == null;
  77434. },
  77435. /**
  77436. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  77437. */
  77438. set: function (enabled) {
  77439. if (enabled && !this._glowLayer) {
  77440. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  77441. }
  77442. else if (!enabled && this._glowLayer) {
  77443. this._glowLayer.dispose();
  77444. this._glowLayer = null;
  77445. }
  77446. },
  77447. enumerable: true,
  77448. configurable: true
  77449. });
  77450. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  77451. get: function () {
  77452. return this._chromaticAberrationEnabled;
  77453. },
  77454. /**
  77455. * Enable or disable the chromaticAberration process from the pipeline
  77456. */
  77457. set: function (enabled) {
  77458. if (this._chromaticAberrationEnabled === enabled) {
  77459. return;
  77460. }
  77461. this._chromaticAberrationEnabled = enabled;
  77462. this._buildPipeline();
  77463. },
  77464. enumerable: true,
  77465. configurable: true
  77466. });
  77467. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  77468. get: function () {
  77469. return this._grainEnabled;
  77470. },
  77471. /**
  77472. * Enable or disable the grain process from the pipeline
  77473. */
  77474. set: function (enabled) {
  77475. if (this._grainEnabled === enabled) {
  77476. return;
  77477. }
  77478. this._grainEnabled = enabled;
  77479. this._buildPipeline();
  77480. },
  77481. enumerable: true,
  77482. configurable: true
  77483. });
  77484. /**
  77485. * Force the compilation of the entire pipeline.
  77486. */
  77487. DefaultRenderingPipeline.prototype.prepare = function () {
  77488. var previousState = this._buildAllowed;
  77489. this._buildAllowed = true;
  77490. this._buildPipeline();
  77491. this._buildAllowed = previousState;
  77492. };
  77493. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  77494. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  77495. if (this._hasCleared) {
  77496. postProcess.autoClear = false;
  77497. }
  77498. else {
  77499. postProcess.autoClear = true;
  77500. this._scene.autoClear = false;
  77501. this._hasCleared = true;
  77502. }
  77503. if (!skipTextureSharing) {
  77504. if (this._prevPrevPostProcess) {
  77505. postProcess.shareOutputWith(this._prevPrevPostProcess);
  77506. }
  77507. else {
  77508. postProcess.useOwnOutput();
  77509. }
  77510. if (this._prevPostProcess) {
  77511. this._prevPrevPostProcess = this._prevPostProcess;
  77512. }
  77513. this._prevPostProcess = postProcess;
  77514. }
  77515. };
  77516. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  77517. var _this = this;
  77518. if (!this._buildAllowed) {
  77519. return;
  77520. }
  77521. this._scene.autoClear = true;
  77522. var engine = this._scene.getEngine();
  77523. this._disposePostProcesses();
  77524. if (this._cameras !== null) {
  77525. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77526. // get back cameras to be used to reattach pipeline
  77527. this._cameras = this._camerasToBeAttached.slice();
  77528. }
  77529. this._reset();
  77530. this._prevPostProcess = null;
  77531. this._prevPrevPostProcess = null;
  77532. this._hasCleared = false;
  77533. if (this.depthOfFieldEnabled) {
  77534. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  77535. this.depthOfField.depthTexture = depthTexture;
  77536. if (!this.depthOfField._isReady()) {
  77537. this.depthOfField._updateEffects();
  77538. }
  77539. this.addEffect(this.depthOfField);
  77540. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  77541. }
  77542. if (this.bloomEnabled) {
  77543. if (!this.bloom._isReady()) {
  77544. this.bloom._updateEffects();
  77545. }
  77546. this.addEffect(this.bloom);
  77547. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  77548. }
  77549. if (this._imageProcessingEnabled) {
  77550. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  77551. if (this._hdr) {
  77552. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  77553. this._setAutoClearAndTextureSharing(this.imageProcessing);
  77554. }
  77555. else {
  77556. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  77557. }
  77558. }
  77559. if (this.sharpenEnabled) {
  77560. if (!this.sharpen.isReady()) {
  77561. this.sharpen.updateEffect();
  77562. }
  77563. this.addEffect(this._sharpenEffect);
  77564. this._setAutoClearAndTextureSharing(this.sharpen);
  77565. }
  77566. if (this.grainEnabled) {
  77567. if (!this.grain.isReady()) {
  77568. this.grain.updateEffect();
  77569. }
  77570. this.addEffect(this._grainEffect);
  77571. this._setAutoClearAndTextureSharing(this.grain);
  77572. }
  77573. if (this.chromaticAberrationEnabled) {
  77574. if (!this.chromaticAberration.isReady()) {
  77575. this.chromaticAberration.updateEffect();
  77576. }
  77577. this.addEffect(this._chromaticAberrationEffect);
  77578. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  77579. }
  77580. if (this.fxaaEnabled) {
  77581. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  77582. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  77583. this._setAutoClearAndTextureSharing(this.fxaa, true);
  77584. }
  77585. if (this._cameras !== null) {
  77586. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  77587. }
  77588. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  77589. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  77590. }
  77591. };
  77592. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  77593. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  77594. for (var i = 0; i < this._cameras.length; i++) {
  77595. var camera = this._cameras[i];
  77596. if (this.imageProcessing) {
  77597. this.imageProcessing.dispose(camera);
  77598. }
  77599. if (this.fxaa) {
  77600. this.fxaa.dispose(camera);
  77601. }
  77602. // These are created in the constructor and should not be disposed on every pipeline change
  77603. if (disposeNonRecreated) {
  77604. if (this.sharpen) {
  77605. this.sharpen.dispose(camera);
  77606. }
  77607. if (this.depthOfField) {
  77608. this.depthOfField.disposeEffects(camera);
  77609. }
  77610. if (this.bloom) {
  77611. this.bloom.disposeEffects(camera);
  77612. }
  77613. if (this.chromaticAberration) {
  77614. this.chromaticAberration.dispose(camera);
  77615. }
  77616. if (this.grain) {
  77617. this.grain.dispose(camera);
  77618. }
  77619. if (this._glowLayer) {
  77620. this._glowLayer.dispose();
  77621. }
  77622. }
  77623. }
  77624. this.imageProcessing = null;
  77625. this.fxaa = null;
  77626. if (disposeNonRecreated) {
  77627. this.sharpen = null;
  77628. this._sharpenEffect = null;
  77629. this.depthOfField = null;
  77630. this.bloom = null;
  77631. this.chromaticAberration = null;
  77632. this._chromaticAberrationEffect = null;
  77633. this.grain = null;
  77634. this._grainEffect = null;
  77635. this._glowLayer = null;
  77636. }
  77637. };
  77638. /**
  77639. * Adds a camera to the pipeline
  77640. * @param camera the camera to be added
  77641. */
  77642. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  77643. this._camerasToBeAttached.push(camera);
  77644. this._buildPipeline();
  77645. };
  77646. /**
  77647. * Removes a camera from the pipeline
  77648. * @param camera the camera to remove
  77649. */
  77650. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  77651. var index = this._camerasToBeAttached.indexOf(camera);
  77652. this._camerasToBeAttached.splice(index, 1);
  77653. this._buildPipeline();
  77654. };
  77655. /**
  77656. * Dispose of the pipeline and stop all post processes
  77657. */
  77658. DefaultRenderingPipeline.prototype.dispose = function () {
  77659. this._disposePostProcesses(true);
  77660. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77661. this._scene.autoClear = true;
  77662. if (this._resizeObserver) {
  77663. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  77664. this._resizeObserver = null;
  77665. }
  77666. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  77667. _super.prototype.dispose.call(this);
  77668. };
  77669. /**
  77670. * Serialize the rendering pipeline (Used when exporting)
  77671. * @returns the serialized object
  77672. */
  77673. DefaultRenderingPipeline.prototype.serialize = function () {
  77674. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77675. serializationObject.customType = "DefaultRenderingPipeline";
  77676. return serializationObject;
  77677. };
  77678. /**
  77679. * Parse the serialized pipeline
  77680. * @param source Source pipeline.
  77681. * @param scene The scene to load the pipeline to.
  77682. * @param rootUrl The URL of the serialized pipeline.
  77683. * @returns An instantiated pipeline from the serialized object.
  77684. */
  77685. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77686. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  77687. };
  77688. __decorate([
  77689. BABYLON.serialize()
  77690. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  77691. __decorate([
  77692. BABYLON.serialize()
  77693. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  77694. __decorate([
  77695. BABYLON.serialize()
  77696. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  77697. __decorate([
  77698. BABYLON.serialize()
  77699. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  77700. __decorate([
  77701. BABYLON.serialize()
  77702. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  77703. __decorate([
  77704. BABYLON.serialize()
  77705. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  77706. __decorate([
  77707. BABYLON.serialize()
  77708. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  77709. __decorate([
  77710. BABYLON.serialize()
  77711. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  77712. __decorate([
  77713. BABYLON.serialize()
  77714. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  77715. __decorate([
  77716. BABYLON.serialize()
  77717. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  77718. __decorate([
  77719. BABYLON.serialize()
  77720. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  77721. __decorate([
  77722. BABYLON.serialize()
  77723. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  77724. __decorate([
  77725. BABYLON.serialize()
  77726. ], DefaultRenderingPipeline.prototype, "samples", null);
  77727. __decorate([
  77728. BABYLON.serialize()
  77729. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  77730. __decorate([
  77731. BABYLON.serialize()
  77732. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77733. __decorate([
  77734. BABYLON.serialize()
  77735. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77736. __decorate([
  77737. BABYLON.serialize()
  77738. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77739. return DefaultRenderingPipeline;
  77740. }(BABYLON.PostProcessRenderPipeline));
  77741. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77742. })(BABYLON || (BABYLON = {}));
  77743. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77744. var BABYLON;
  77745. (function (BABYLON) {
  77746. /**
  77747. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77748. */
  77749. var GeometryBufferRenderer = /** @class */ (function () {
  77750. /**
  77751. * Creates a new G Buffer for the scene
  77752. * @param scene The scene the buffer belongs to
  77753. * @param ratio How big is the buffer related to the main canvas.
  77754. */
  77755. function GeometryBufferRenderer(scene, ratio) {
  77756. if (ratio === void 0) { ratio = 1; }
  77757. this._enablePosition = false;
  77758. this._scene = scene;
  77759. this._ratio = ratio;
  77760. // Render target
  77761. this._createRenderTargets();
  77762. }
  77763. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77764. /**
  77765. * Set the render list (meshes to be rendered) used in the G buffer.
  77766. */
  77767. set: function (meshes) {
  77768. this._multiRenderTarget.renderList = meshes;
  77769. },
  77770. enumerable: true,
  77771. configurable: true
  77772. });
  77773. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77774. /**
  77775. * Gets wether or not G buffer are supported by the running hardware.
  77776. * This requires draw buffer supports
  77777. */
  77778. get: function () {
  77779. return this._multiRenderTarget.isSupported;
  77780. },
  77781. enumerable: true,
  77782. configurable: true
  77783. });
  77784. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77785. /**
  77786. * Gets wether or not position are enabled for the G buffer.
  77787. */
  77788. get: function () {
  77789. return this._enablePosition;
  77790. },
  77791. /**
  77792. * Sets wether or not position are enabled for the G buffer.
  77793. */
  77794. set: function (enable) {
  77795. this._enablePosition = enable;
  77796. this.dispose();
  77797. this._createRenderTargets();
  77798. },
  77799. enumerable: true,
  77800. configurable: true
  77801. });
  77802. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77803. /**
  77804. * Gets the scene associated with the buffer.
  77805. */
  77806. get: function () {
  77807. return this._scene;
  77808. },
  77809. enumerable: true,
  77810. configurable: true
  77811. });
  77812. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77813. /**
  77814. * Gets the ratio used by the buffer during its creation.
  77815. * How big is the buffer related to the main canvas.
  77816. */
  77817. get: function () {
  77818. return this._ratio;
  77819. },
  77820. enumerable: true,
  77821. configurable: true
  77822. });
  77823. /**
  77824. * Checks wether everything is ready to render a submesh to the G buffer.
  77825. * @param subMesh the submesh to check readiness for
  77826. * @param useInstances is the mesh drawn using instance or not
  77827. * @returns true if ready otherwise false
  77828. */
  77829. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77830. var material = subMesh.getMaterial();
  77831. if (material && material.disableDepthWrite) {
  77832. return false;
  77833. }
  77834. var defines = [];
  77835. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77836. var mesh = subMesh.getMesh();
  77837. // Alpha test
  77838. if (material && material.needAlphaTesting()) {
  77839. defines.push("#define ALPHATEST");
  77840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77841. attribs.push(BABYLON.VertexBuffer.UVKind);
  77842. defines.push("#define UV1");
  77843. }
  77844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77845. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77846. defines.push("#define UV2");
  77847. }
  77848. }
  77849. // Buffers
  77850. if (this._enablePosition) {
  77851. defines.push("#define POSITION");
  77852. }
  77853. // Bones
  77854. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77855. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77856. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77857. if (mesh.numBoneInfluencers > 4) {
  77858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77860. }
  77861. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77862. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77863. }
  77864. else {
  77865. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77866. }
  77867. // Instances
  77868. if (useInstances) {
  77869. defines.push("#define INSTANCES");
  77870. attribs.push("world0");
  77871. attribs.push("world1");
  77872. attribs.push("world2");
  77873. attribs.push("world3");
  77874. }
  77875. // Get correct effect
  77876. var join = defines.join("\n");
  77877. if (this._cachedDefines !== join) {
  77878. this._cachedDefines = join;
  77879. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77880. }
  77881. return this._effect.isReady();
  77882. };
  77883. /**
  77884. * Gets the current underlying G Buffer.
  77885. * @returns the buffer
  77886. */
  77887. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77888. return this._multiRenderTarget;
  77889. };
  77890. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77891. /**
  77892. * Gets the number of samples used to render the buffer (anti aliasing).
  77893. */
  77894. get: function () {
  77895. return this._multiRenderTarget.samples;
  77896. },
  77897. /**
  77898. * Sets the number of samples used to render the buffer (anti aliasing).
  77899. */
  77900. set: function (value) {
  77901. this._multiRenderTarget.samples = value;
  77902. },
  77903. enumerable: true,
  77904. configurable: true
  77905. });
  77906. /**
  77907. * Disposes the renderer and frees up associated resources.
  77908. */
  77909. GeometryBufferRenderer.prototype.dispose = function () {
  77910. this.getGBuffer().dispose();
  77911. };
  77912. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77913. var _this = this;
  77914. var engine = this._scene.getEngine();
  77915. var count = this._enablePosition ? 3 : 2;
  77916. 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 });
  77917. if (!this.isSupported) {
  77918. return;
  77919. }
  77920. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77921. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77922. this._multiRenderTarget.refreshRate = 1;
  77923. this._multiRenderTarget.renderParticles = false;
  77924. this._multiRenderTarget.renderList = null;
  77925. // set default depth value to 1.0 (far away)
  77926. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77927. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77928. });
  77929. // Custom render function
  77930. var renderSubMesh = function (subMesh) {
  77931. var mesh = subMesh.getRenderingMesh();
  77932. var scene = _this._scene;
  77933. var engine = scene.getEngine();
  77934. var material = subMesh.getMaterial();
  77935. if (!material) {
  77936. return;
  77937. }
  77938. // Culling
  77939. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77940. // Managing instances
  77941. var batch = mesh._getInstancesRenderList(subMesh._id);
  77942. if (batch.mustReturn) {
  77943. return;
  77944. }
  77945. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77946. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77947. engine.enableEffect(_this._effect);
  77948. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77949. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77950. _this._effect.setMatrix("view", scene.getViewMatrix());
  77951. // Alpha test
  77952. if (material && material.needAlphaTesting()) {
  77953. var alphaTexture = material.getAlphaTestTexture();
  77954. if (alphaTexture) {
  77955. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77956. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77957. }
  77958. }
  77959. // Bones
  77960. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77961. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77962. }
  77963. // Draw
  77964. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77965. }
  77966. };
  77967. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77968. var index;
  77969. if (depthOnlySubMeshes.length) {
  77970. engine.setColorWrite(false);
  77971. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77972. renderSubMesh(depthOnlySubMeshes.data[index]);
  77973. }
  77974. engine.setColorWrite(true);
  77975. }
  77976. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77977. renderSubMesh(opaqueSubMeshes.data[index]);
  77978. }
  77979. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77980. renderSubMesh(alphaTestSubMeshes.data[index]);
  77981. }
  77982. };
  77983. };
  77984. return GeometryBufferRenderer;
  77985. }());
  77986. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77987. })(BABYLON || (BABYLON = {}));
  77988. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77989. var BABYLON;
  77990. (function (BABYLON) {
  77991. /**
  77992. * This groups together the common properties used for image processing either in direct forward pass
  77993. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77994. * or not.
  77995. */
  77996. var ImageProcessingConfiguration = /** @class */ (function () {
  77997. function ImageProcessingConfiguration() {
  77998. /**
  77999. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78000. */
  78001. this.colorCurves = new BABYLON.ColorCurves();
  78002. this._colorCurvesEnabled = false;
  78003. this._colorGradingEnabled = false;
  78004. this._colorGradingWithGreenDepth = true;
  78005. this._colorGradingBGR = true;
  78006. this._exposure = 1.0;
  78007. this._toneMappingEnabled = false;
  78008. this._contrast = 1.0;
  78009. /**
  78010. * Vignette stretch size.
  78011. */
  78012. this.vignetteStretch = 0;
  78013. /**
  78014. * Vignette centre X Offset.
  78015. */
  78016. this.vignetteCentreX = 0;
  78017. /**
  78018. * Vignette centre Y Offset.
  78019. */
  78020. this.vignetteCentreY = 0;
  78021. /**
  78022. * Vignette weight or intensity of the vignette effect.
  78023. */
  78024. this.vignetteWeight = 1.5;
  78025. /**
  78026. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78027. * if vignetteEnabled is set to true.
  78028. */
  78029. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78030. /**
  78031. * Camera field of view used by the Vignette effect.
  78032. */
  78033. this.vignetteCameraFov = 0.5;
  78034. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78035. this._vignetteEnabled = false;
  78036. this._applyByPostProcess = false;
  78037. this._isEnabled = true;
  78038. /**
  78039. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78040. */
  78041. this.onUpdateParameters = new BABYLON.Observable();
  78042. }
  78043. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78044. /**
  78045. * Gets wether the color curves effect is enabled.
  78046. */
  78047. get: function () {
  78048. return this._colorCurvesEnabled;
  78049. },
  78050. /**
  78051. * Sets wether the color curves effect is enabled.
  78052. */
  78053. set: function (value) {
  78054. if (this._colorCurvesEnabled === value) {
  78055. return;
  78056. }
  78057. this._colorCurvesEnabled = value;
  78058. this._updateParameters();
  78059. },
  78060. enumerable: true,
  78061. configurable: true
  78062. });
  78063. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78064. /**
  78065. * Gets wether the color grading effect is enabled.
  78066. */
  78067. get: function () {
  78068. return this._colorGradingEnabled;
  78069. },
  78070. /**
  78071. * Sets wether the color grading effect is enabled.
  78072. */
  78073. set: function (value) {
  78074. if (this._colorGradingEnabled === value) {
  78075. return;
  78076. }
  78077. this._colorGradingEnabled = value;
  78078. this._updateParameters();
  78079. },
  78080. enumerable: true,
  78081. configurable: true
  78082. });
  78083. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  78084. /**
  78085. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  78086. */
  78087. get: function () {
  78088. return this._colorGradingWithGreenDepth;
  78089. },
  78090. /**
  78091. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  78092. */
  78093. set: function (value) {
  78094. if (this._colorGradingWithGreenDepth === value) {
  78095. return;
  78096. }
  78097. this._colorGradingWithGreenDepth = value;
  78098. this._updateParameters();
  78099. },
  78100. enumerable: true,
  78101. configurable: true
  78102. });
  78103. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  78104. /**
  78105. * Gets wether the color grading texture contains BGR values.
  78106. */
  78107. get: function () {
  78108. return this._colorGradingBGR;
  78109. },
  78110. /**
  78111. * Sets wether the color grading texture contains BGR values.
  78112. */
  78113. set: function (value) {
  78114. if (this._colorGradingBGR === value) {
  78115. return;
  78116. }
  78117. this._colorGradingBGR = value;
  78118. this._updateParameters();
  78119. },
  78120. enumerable: true,
  78121. configurable: true
  78122. });
  78123. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  78124. /**
  78125. * Gets the Exposure used in the effect.
  78126. */
  78127. get: function () {
  78128. return this._exposure;
  78129. },
  78130. /**
  78131. * Sets the Exposure used in the effect.
  78132. */
  78133. set: function (value) {
  78134. if (this._exposure === value) {
  78135. return;
  78136. }
  78137. this._exposure = value;
  78138. this._updateParameters();
  78139. },
  78140. enumerable: true,
  78141. configurable: true
  78142. });
  78143. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  78144. /**
  78145. * Gets wether the tone mapping effect is enabled.
  78146. */
  78147. get: function () {
  78148. return this._toneMappingEnabled;
  78149. },
  78150. /**
  78151. * Sets wether the tone mapping effect is enabled.
  78152. */
  78153. set: function (value) {
  78154. if (this._toneMappingEnabled === value) {
  78155. return;
  78156. }
  78157. this._toneMappingEnabled = value;
  78158. this._updateParameters();
  78159. },
  78160. enumerable: true,
  78161. configurable: true
  78162. });
  78163. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  78164. /**
  78165. * Gets the contrast used in the effect.
  78166. */
  78167. get: function () {
  78168. return this._contrast;
  78169. },
  78170. /**
  78171. * Sets the contrast used in the effect.
  78172. */
  78173. set: function (value) {
  78174. if (this._contrast === value) {
  78175. return;
  78176. }
  78177. this._contrast = value;
  78178. this._updateParameters();
  78179. },
  78180. enumerable: true,
  78181. configurable: true
  78182. });
  78183. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  78184. /**
  78185. * Gets the vignette blend mode allowing different kind of effect.
  78186. */
  78187. get: function () {
  78188. return this._vignetteBlendMode;
  78189. },
  78190. /**
  78191. * Sets the vignette blend mode allowing different kind of effect.
  78192. */
  78193. set: function (value) {
  78194. if (this._vignetteBlendMode === value) {
  78195. return;
  78196. }
  78197. this._vignetteBlendMode = value;
  78198. this._updateParameters();
  78199. },
  78200. enumerable: true,
  78201. configurable: true
  78202. });
  78203. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  78204. /**
  78205. * Gets wether the vignette effect is enabled.
  78206. */
  78207. get: function () {
  78208. return this._vignetteEnabled;
  78209. },
  78210. /**
  78211. * Sets wether the vignette effect is enabled.
  78212. */
  78213. set: function (value) {
  78214. if (this._vignetteEnabled === value) {
  78215. return;
  78216. }
  78217. this._vignetteEnabled = value;
  78218. this._updateParameters();
  78219. },
  78220. enumerable: true,
  78221. configurable: true
  78222. });
  78223. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  78224. /**
  78225. * Gets wether the image processing is applied through a post process or not.
  78226. */
  78227. get: function () {
  78228. return this._applyByPostProcess;
  78229. },
  78230. /**
  78231. * Sets wether the image processing is applied through a post process or not.
  78232. */
  78233. set: function (value) {
  78234. if (this._applyByPostProcess === value) {
  78235. return;
  78236. }
  78237. this._applyByPostProcess = value;
  78238. this._updateParameters();
  78239. },
  78240. enumerable: true,
  78241. configurable: true
  78242. });
  78243. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  78244. /**
  78245. * Gets wether the image processing is enabled or not.
  78246. */
  78247. get: function () {
  78248. return this._isEnabled;
  78249. },
  78250. /**
  78251. * Sets wether the image processing is enabled or not.
  78252. */
  78253. set: function (value) {
  78254. if (this._isEnabled === value) {
  78255. return;
  78256. }
  78257. this._isEnabled = value;
  78258. this._updateParameters();
  78259. },
  78260. enumerable: true,
  78261. configurable: true
  78262. });
  78263. /**
  78264. * Method called each time the image processing information changes requires to recompile the effect.
  78265. */
  78266. ImageProcessingConfiguration.prototype._updateParameters = function () {
  78267. this.onUpdateParameters.notifyObservers(this);
  78268. };
  78269. ImageProcessingConfiguration.prototype.getClassName = function () {
  78270. return "ImageProcessingConfiguration";
  78271. };
  78272. /**
  78273. * Prepare the list of uniforms associated with the Image Processing effects.
  78274. * @param uniformsList The list of uniforms used in the effect
  78275. * @param defines the list of defines currently in use
  78276. */
  78277. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  78278. if (defines.EXPOSURE) {
  78279. uniforms.push("exposureLinear");
  78280. }
  78281. if (defines.CONTRAST) {
  78282. uniforms.push("contrast");
  78283. }
  78284. if (defines.COLORGRADING) {
  78285. uniforms.push("colorTransformSettings");
  78286. }
  78287. if (defines.VIGNETTE) {
  78288. uniforms.push("vInverseScreenSize");
  78289. uniforms.push("vignetteSettings1");
  78290. uniforms.push("vignetteSettings2");
  78291. }
  78292. if (defines.COLORCURVES) {
  78293. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  78294. }
  78295. };
  78296. /**
  78297. * Prepare the list of samplers associated with the Image Processing effects.
  78298. * @param uniformsList The list of uniforms used in the effect
  78299. * @param defines the list of defines currently in use
  78300. */
  78301. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  78302. if (defines.COLORGRADING) {
  78303. samplersList.push("txColorTransform");
  78304. }
  78305. };
  78306. /**
  78307. * Prepare the list of defines associated to the shader.
  78308. * @param defines the list of defines to complete
  78309. */
  78310. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  78311. if (forPostProcess === void 0) { forPostProcess = false; }
  78312. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  78313. defines.VIGNETTE = false;
  78314. defines.TONEMAPPING = false;
  78315. defines.CONTRAST = false;
  78316. defines.EXPOSURE = false;
  78317. defines.COLORCURVES = false;
  78318. defines.COLORGRADING = false;
  78319. defines.COLORGRADING3D = false;
  78320. defines.IMAGEPROCESSING = false;
  78321. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  78322. return;
  78323. }
  78324. defines.VIGNETTE = this.vignetteEnabled;
  78325. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  78326. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  78327. defines.TONEMAPPING = this.toneMappingEnabled;
  78328. defines.CONTRAST = (this.contrast !== 1.0);
  78329. defines.EXPOSURE = (this.exposure !== 1.0);
  78330. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  78331. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  78332. if (defines.COLORGRADING) {
  78333. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  78334. }
  78335. else {
  78336. defines.COLORGRADING3D = false;
  78337. }
  78338. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  78339. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  78340. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  78341. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  78342. };
  78343. /**
  78344. * Returns true if all the image processing information are ready.
  78345. */
  78346. ImageProcessingConfiguration.prototype.isReady = function () {
  78347. // Color Grading texure can not be none blocking.
  78348. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  78349. };
  78350. /**
  78351. * Binds the image processing to the shader.
  78352. * @param effect The effect to bind to
  78353. */
  78354. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  78355. if (aspectRatio === void 0) { aspectRatio = 1; }
  78356. // Color Curves
  78357. if (this._colorCurvesEnabled && this.colorCurves) {
  78358. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  78359. }
  78360. // Vignette
  78361. if (this._vignetteEnabled) {
  78362. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  78363. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  78364. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  78365. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  78366. var vignetteScaleX = vignetteScaleY * aspectRatio;
  78367. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  78368. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  78369. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  78370. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  78371. var vignettePower = -2.0 * this.vignetteWeight;
  78372. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  78373. }
  78374. // Exposure
  78375. effect.setFloat("exposureLinear", this.exposure);
  78376. // Contrast
  78377. effect.setFloat("contrast", this.contrast);
  78378. // Color transform settings
  78379. if (this.colorGradingTexture) {
  78380. effect.setTexture("txColorTransform", this.colorGradingTexture);
  78381. var textureSize = this.colorGradingTexture.getSize().height;
  78382. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  78383. 0.5 / textureSize, // textureOffset
  78384. textureSize, // textureSize
  78385. this.colorGradingTexture.level // weight
  78386. );
  78387. }
  78388. };
  78389. /**
  78390. * Clones the current image processing instance.
  78391. * @return The cloned image processing
  78392. */
  78393. ImageProcessingConfiguration.prototype.clone = function () {
  78394. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  78395. };
  78396. /**
  78397. * Serializes the current image processing instance to a json representation.
  78398. * @return a JSON representation
  78399. */
  78400. ImageProcessingConfiguration.prototype.serialize = function () {
  78401. return BABYLON.SerializationHelper.Serialize(this);
  78402. };
  78403. /**
  78404. * Parses the image processing from a json representation.
  78405. * @param source the JSON source to parse
  78406. * @return The parsed image processing
  78407. */
  78408. ImageProcessingConfiguration.Parse = function (source) {
  78409. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  78410. };
  78411. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  78412. /**
  78413. * Used to apply the vignette as a mix with the pixel color.
  78414. */
  78415. get: function () {
  78416. return this._VIGNETTEMODE_MULTIPLY;
  78417. },
  78418. enumerable: true,
  78419. configurable: true
  78420. });
  78421. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  78422. /**
  78423. * Used to apply the vignette as a replacement of the pixel color.
  78424. */
  78425. get: function () {
  78426. return this._VIGNETTEMODE_OPAQUE;
  78427. },
  78428. enumerable: true,
  78429. configurable: true
  78430. });
  78431. // Static constants associated to the image processing.
  78432. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  78433. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  78434. __decorate([
  78435. BABYLON.serializeAsColorCurves()
  78436. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  78437. __decorate([
  78438. BABYLON.serialize()
  78439. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  78440. __decorate([
  78441. BABYLON.serializeAsTexture()
  78442. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  78443. __decorate([
  78444. BABYLON.serialize()
  78445. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  78446. __decorate([
  78447. BABYLON.serialize()
  78448. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  78449. __decorate([
  78450. BABYLON.serialize()
  78451. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  78452. __decorate([
  78453. BABYLON.serialize()
  78454. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  78455. __decorate([
  78456. BABYLON.serialize()
  78457. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  78458. __decorate([
  78459. BABYLON.serialize()
  78460. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  78461. __decorate([
  78462. BABYLON.serialize()
  78463. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  78464. __decorate([
  78465. BABYLON.serialize()
  78466. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  78467. __decorate([
  78468. BABYLON.serialize()
  78469. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  78470. __decorate([
  78471. BABYLON.serialize()
  78472. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  78473. __decorate([
  78474. BABYLON.serializeAsColor4()
  78475. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  78476. __decorate([
  78477. BABYLON.serialize()
  78478. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  78479. __decorate([
  78480. BABYLON.serialize()
  78481. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  78482. __decorate([
  78483. BABYLON.serialize()
  78484. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  78485. __decorate([
  78486. BABYLON.serialize()
  78487. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  78488. __decorate([
  78489. BABYLON.serialize()
  78490. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  78491. return ImageProcessingConfiguration;
  78492. }());
  78493. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  78494. })(BABYLON || (BABYLON = {}));
  78495. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  78496. var BABYLON;
  78497. (function (BABYLON) {
  78498. /**
  78499. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  78500. * It can help converting any input color in a desired output one. This can then be used to create effects
  78501. * from sepia, black and white to sixties or futuristic rendering...
  78502. *
  78503. * The only supported format is currently 3dl.
  78504. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  78505. */
  78506. var ColorGradingTexture = /** @class */ (function (_super) {
  78507. __extends(ColorGradingTexture, _super);
  78508. /**
  78509. * Instantiates a ColorGradingTexture from the following parameters.
  78510. *
  78511. * @param url The location of the color gradind data (currently only supporting 3dl)
  78512. * @param scene The scene the texture will be used in
  78513. */
  78514. function ColorGradingTexture(url, scene) {
  78515. var _this = _super.call(this, scene) || this;
  78516. if (!url) {
  78517. return _this;
  78518. }
  78519. _this._engine = scene.getEngine();
  78520. _this._textureMatrix = BABYLON.Matrix.Identity();
  78521. _this.name = url;
  78522. _this.url = url;
  78523. _this.hasAlpha = false;
  78524. _this.isCube = false;
  78525. _this.is3D = _this._engine.webGLVersion > 1;
  78526. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78527. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78528. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78529. _this.anisotropicFilteringLevel = 1;
  78530. _this._texture = _this._getFromCache(url, true);
  78531. if (!_this._texture) {
  78532. if (!scene.useDelayedTextureLoading) {
  78533. _this.loadTexture();
  78534. }
  78535. else {
  78536. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78537. }
  78538. }
  78539. return _this;
  78540. }
  78541. /**
  78542. * Returns the texture matrix used in most of the material.
  78543. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  78544. */
  78545. ColorGradingTexture.prototype.getTextureMatrix = function () {
  78546. return this._textureMatrix;
  78547. };
  78548. /**
  78549. * Occurs when the file being loaded is a .3dl LUT file.
  78550. */
  78551. ColorGradingTexture.prototype.load3dlTexture = function () {
  78552. var engine = this._engine;
  78553. var texture;
  78554. if (engine.webGLVersion === 1) {
  78555. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78556. }
  78557. else {
  78558. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78559. }
  78560. this._texture = texture;
  78561. var callback = function (text) {
  78562. if (typeof text !== "string") {
  78563. return;
  78564. }
  78565. var data = null;
  78566. var tempData = null;
  78567. var line;
  78568. var lines = text.split('\n');
  78569. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  78570. var maxColor = 0;
  78571. for (var i = 0; i < lines.length; i++) {
  78572. line = lines[i];
  78573. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  78574. continue;
  78575. if (line.indexOf('#') === 0)
  78576. continue;
  78577. var words = line.split(" ");
  78578. if (size === 0) {
  78579. // Number of space + one
  78580. size = words.length;
  78581. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  78582. tempData = new Float32Array(size * size * size * 4);
  78583. continue;
  78584. }
  78585. if (size != 0) {
  78586. var r = Math.max(parseInt(words[0]), 0);
  78587. var g = Math.max(parseInt(words[1]), 0);
  78588. var b = Math.max(parseInt(words[2]), 0);
  78589. maxColor = Math.max(r, maxColor);
  78590. maxColor = Math.max(g, maxColor);
  78591. maxColor = Math.max(b, maxColor);
  78592. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  78593. if (tempData) {
  78594. tempData[pixelStorageIndex + 0] = r;
  78595. tempData[pixelStorageIndex + 1] = g;
  78596. tempData[pixelStorageIndex + 2] = b;
  78597. }
  78598. pixelIndexSlice++;
  78599. if (pixelIndexSlice % size == 0) {
  78600. pixelIndexH++;
  78601. pixelIndexSlice = 0;
  78602. if (pixelIndexH % size == 0) {
  78603. pixelIndexW++;
  78604. pixelIndexH = 0;
  78605. }
  78606. }
  78607. }
  78608. }
  78609. if (tempData && data) {
  78610. for (var i = 0; i < tempData.length; i++) {
  78611. if (i > 0 && (i + 1) % 4 === 0) {
  78612. data[i] = 255;
  78613. }
  78614. else {
  78615. var value = tempData[i];
  78616. data[i] = (value / maxColor * 255);
  78617. }
  78618. }
  78619. }
  78620. if (texture.is3D) {
  78621. texture.updateSize(size, size, size);
  78622. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78623. }
  78624. else {
  78625. texture.updateSize(size * size, size);
  78626. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  78627. }
  78628. };
  78629. var scene = this.getScene();
  78630. if (scene) {
  78631. scene._loadFile(this.url, callback);
  78632. }
  78633. else {
  78634. this._engine._loadFile(this.url, callback);
  78635. }
  78636. return this._texture;
  78637. };
  78638. /**
  78639. * Starts the loading process of the texture.
  78640. */
  78641. ColorGradingTexture.prototype.loadTexture = function () {
  78642. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  78643. this.load3dlTexture();
  78644. }
  78645. };
  78646. /**
  78647. * Clones the color gradind texture.
  78648. */
  78649. ColorGradingTexture.prototype.clone = function () {
  78650. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  78651. // Base texture
  78652. newTexture.level = this.level;
  78653. return newTexture;
  78654. };
  78655. /**
  78656. * Called during delayed load for textures.
  78657. */
  78658. ColorGradingTexture.prototype.delayLoad = function () {
  78659. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78660. return;
  78661. }
  78662. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78663. this._texture = this._getFromCache(this.url, true);
  78664. if (!this._texture) {
  78665. this.loadTexture();
  78666. }
  78667. };
  78668. /**
  78669. * Parses a color grading texture serialized by Babylon.
  78670. * @param parsedTexture The texture information being parsedTexture
  78671. * @param scene The scene to load the texture in
  78672. * @param rootUrl The root url of the data assets to load
  78673. * @return A color gradind texture
  78674. */
  78675. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78676. var texture = null;
  78677. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78678. texture = new ColorGradingTexture(parsedTexture.name, scene);
  78679. texture.name = parsedTexture.name;
  78680. texture.level = parsedTexture.level;
  78681. }
  78682. return texture;
  78683. };
  78684. /**
  78685. * Serializes the LUT texture to json format.
  78686. */
  78687. ColorGradingTexture.prototype.serialize = function () {
  78688. if (!this.name) {
  78689. return null;
  78690. }
  78691. var serializationObject = {};
  78692. serializationObject.name = this.name;
  78693. serializationObject.level = this.level;
  78694. serializationObject.customType = "BABYLON.ColorGradingTexture";
  78695. return serializationObject;
  78696. };
  78697. /**
  78698. * Empty line regex stored for GC.
  78699. */
  78700. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  78701. return ColorGradingTexture;
  78702. }(BABYLON.BaseTexture));
  78703. BABYLON.ColorGradingTexture = ColorGradingTexture;
  78704. })(BABYLON || (BABYLON = {}));
  78705. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  78706. var BABYLON;
  78707. (function (BABYLON) {
  78708. /**
  78709. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78710. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78711. * 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;
  78712. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78713. */
  78714. var ColorCurves = /** @class */ (function () {
  78715. function ColorCurves() {
  78716. this._dirty = true;
  78717. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  78718. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  78719. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78720. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  78721. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78722. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  78723. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  78724. this._globalHue = 30;
  78725. this._globalDensity = 0;
  78726. this._globalSaturation = 0;
  78727. this._globalExposure = 0;
  78728. this._highlightsHue = 30;
  78729. this._highlightsDensity = 0;
  78730. this._highlightsSaturation = 0;
  78731. this._highlightsExposure = 0;
  78732. this._midtonesHue = 30;
  78733. this._midtonesDensity = 0;
  78734. this._midtonesSaturation = 0;
  78735. this._midtonesExposure = 0;
  78736. this._shadowsHue = 30;
  78737. this._shadowsDensity = 0;
  78738. this._shadowsSaturation = 0;
  78739. this._shadowsExposure = 0;
  78740. }
  78741. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  78742. /**
  78743. * Gets the global Hue value.
  78744. * 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).
  78745. */
  78746. get: function () {
  78747. return this._globalHue;
  78748. },
  78749. /**
  78750. * Sets the global Hue value.
  78751. * 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).
  78752. */
  78753. set: function (value) {
  78754. this._globalHue = value;
  78755. this._dirty = true;
  78756. },
  78757. enumerable: true,
  78758. configurable: true
  78759. });
  78760. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  78761. /**
  78762. * Gets the global Density value.
  78763. * 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.
  78764. * Values less than zero provide a filter of opposite hue.
  78765. */
  78766. get: function () {
  78767. return this._globalDensity;
  78768. },
  78769. /**
  78770. * Sets the global Density value.
  78771. * 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.
  78772. * Values less than zero provide a filter of opposite hue.
  78773. */
  78774. set: function (value) {
  78775. this._globalDensity = value;
  78776. this._dirty = true;
  78777. },
  78778. enumerable: true,
  78779. configurable: true
  78780. });
  78781. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78782. /**
  78783. * Gets the global Saturation value.
  78784. * 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.
  78785. */
  78786. get: function () {
  78787. return this._globalSaturation;
  78788. },
  78789. /**
  78790. * Sets the global Saturation value.
  78791. * 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.
  78792. */
  78793. set: function (value) {
  78794. this._globalSaturation = value;
  78795. this._dirty = true;
  78796. },
  78797. enumerable: true,
  78798. configurable: true
  78799. });
  78800. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78801. /**
  78802. * Gets the global Exposure value.
  78803. * 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.
  78804. */
  78805. get: function () {
  78806. return this._globalExposure;
  78807. },
  78808. /**
  78809. * Sets the global Exposure value.
  78810. * 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.
  78811. */
  78812. set: function (value) {
  78813. this._globalExposure = value;
  78814. this._dirty = true;
  78815. },
  78816. enumerable: true,
  78817. configurable: true
  78818. });
  78819. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78820. /**
  78821. * Gets the highlights Hue value.
  78822. * 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).
  78823. */
  78824. get: function () {
  78825. return this._highlightsHue;
  78826. },
  78827. /**
  78828. * Sets the highlights Hue value.
  78829. * 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).
  78830. */
  78831. set: function (value) {
  78832. this._highlightsHue = value;
  78833. this._dirty = true;
  78834. },
  78835. enumerable: true,
  78836. configurable: true
  78837. });
  78838. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78839. /**
  78840. * Gets the highlights Density value.
  78841. * 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.
  78842. * Values less than zero provide a filter of opposite hue.
  78843. */
  78844. get: function () {
  78845. return this._highlightsDensity;
  78846. },
  78847. /**
  78848. * Sets the highlights Density value.
  78849. * 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.
  78850. * Values less than zero provide a filter of opposite hue.
  78851. */
  78852. set: function (value) {
  78853. this._highlightsDensity = value;
  78854. this._dirty = true;
  78855. },
  78856. enumerable: true,
  78857. configurable: true
  78858. });
  78859. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78860. /**
  78861. * Gets the highlights Saturation value.
  78862. * 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.
  78863. */
  78864. get: function () {
  78865. return this._highlightsSaturation;
  78866. },
  78867. /**
  78868. * Sets the highlights Saturation value.
  78869. * 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.
  78870. */
  78871. set: function (value) {
  78872. this._highlightsSaturation = value;
  78873. this._dirty = true;
  78874. },
  78875. enumerable: true,
  78876. configurable: true
  78877. });
  78878. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78879. /**
  78880. * Gets the highlights Exposure value.
  78881. * 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.
  78882. */
  78883. get: function () {
  78884. return this._highlightsExposure;
  78885. },
  78886. /**
  78887. * Sets the highlights Exposure value.
  78888. * 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.
  78889. */
  78890. set: function (value) {
  78891. this._highlightsExposure = value;
  78892. this._dirty = true;
  78893. },
  78894. enumerable: true,
  78895. configurable: true
  78896. });
  78897. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78898. /**
  78899. * Gets the midtones Hue value.
  78900. * 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).
  78901. */
  78902. get: function () {
  78903. return this._midtonesHue;
  78904. },
  78905. /**
  78906. * Sets the midtones Hue value.
  78907. * 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).
  78908. */
  78909. set: function (value) {
  78910. this._midtonesHue = value;
  78911. this._dirty = true;
  78912. },
  78913. enumerable: true,
  78914. configurable: true
  78915. });
  78916. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78917. /**
  78918. * Gets the midtones Density value.
  78919. * 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.
  78920. * Values less than zero provide a filter of opposite hue.
  78921. */
  78922. get: function () {
  78923. return this._midtonesDensity;
  78924. },
  78925. /**
  78926. * Sets the midtones Density value.
  78927. * 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.
  78928. * Values less than zero provide a filter of opposite hue.
  78929. */
  78930. set: function (value) {
  78931. this._midtonesDensity = value;
  78932. this._dirty = true;
  78933. },
  78934. enumerable: true,
  78935. configurable: true
  78936. });
  78937. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78938. /**
  78939. * Gets the midtones Saturation value.
  78940. * 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.
  78941. */
  78942. get: function () {
  78943. return this._midtonesSaturation;
  78944. },
  78945. /**
  78946. * Sets the midtones Saturation value.
  78947. * 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.
  78948. */
  78949. set: function (value) {
  78950. this._midtonesSaturation = value;
  78951. this._dirty = true;
  78952. },
  78953. enumerable: true,
  78954. configurable: true
  78955. });
  78956. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78957. /**
  78958. * Gets the midtones Exposure value.
  78959. * 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.
  78960. */
  78961. get: function () {
  78962. return this._midtonesExposure;
  78963. },
  78964. /**
  78965. * Sets the midtones Exposure value.
  78966. * 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.
  78967. */
  78968. set: function (value) {
  78969. this._midtonesExposure = value;
  78970. this._dirty = true;
  78971. },
  78972. enumerable: true,
  78973. configurable: true
  78974. });
  78975. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78976. /**
  78977. * Gets the shadows Hue value.
  78978. * 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).
  78979. */
  78980. get: function () {
  78981. return this._shadowsHue;
  78982. },
  78983. /**
  78984. * Sets the shadows Hue value.
  78985. * 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).
  78986. */
  78987. set: function (value) {
  78988. this._shadowsHue = value;
  78989. this._dirty = true;
  78990. },
  78991. enumerable: true,
  78992. configurable: true
  78993. });
  78994. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78995. /**
  78996. * Gets the shadows Density value.
  78997. * 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.
  78998. * Values less than zero provide a filter of opposite hue.
  78999. */
  79000. get: function () {
  79001. return this._shadowsDensity;
  79002. },
  79003. /**
  79004. * Sets the shadows Density value.
  79005. * 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.
  79006. * Values less than zero provide a filter of opposite hue.
  79007. */
  79008. set: function (value) {
  79009. this._shadowsDensity = value;
  79010. this._dirty = true;
  79011. },
  79012. enumerable: true,
  79013. configurable: true
  79014. });
  79015. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79016. /**
  79017. * Gets the shadows Saturation value.
  79018. * 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.
  79019. */
  79020. get: function () {
  79021. return this._shadowsSaturation;
  79022. },
  79023. /**
  79024. * Sets the shadows Saturation value.
  79025. * 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.
  79026. */
  79027. set: function (value) {
  79028. this._shadowsSaturation = value;
  79029. this._dirty = true;
  79030. },
  79031. enumerable: true,
  79032. configurable: true
  79033. });
  79034. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79035. /**
  79036. * Gets the shadows Exposure value.
  79037. * 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.
  79038. */
  79039. get: function () {
  79040. return this._shadowsExposure;
  79041. },
  79042. /**
  79043. * Sets the shadows Exposure value.
  79044. * 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.
  79045. */
  79046. set: function (value) {
  79047. this._shadowsExposure = value;
  79048. this._dirty = true;
  79049. },
  79050. enumerable: true,
  79051. configurable: true
  79052. });
  79053. ColorCurves.prototype.getClassName = function () {
  79054. return "ColorCurves";
  79055. };
  79056. /**
  79057. * Binds the color curves to the shader.
  79058. * @param colorCurves The color curve to bind
  79059. * @param effect The effect to bind to
  79060. */
  79061. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79062. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79063. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79064. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79065. if (colorCurves._dirty) {
  79066. colorCurves._dirty = false;
  79067. // Fill in global info.
  79068. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79069. // Compute highlights info.
  79070. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79071. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79072. // Compute midtones info.
  79073. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79074. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79075. // Compute shadows info.
  79076. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79077. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  79078. // Compute deltas (neutral is midtones).
  79079. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  79080. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  79081. }
  79082. if (effect) {
  79083. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  79084. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  79085. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  79086. }
  79087. };
  79088. /**
  79089. * Prepare the list of uniforms associated with the ColorCurves effects.
  79090. * @param uniformsList The list of uniforms used in the effect
  79091. */
  79092. ColorCurves.PrepareUniforms = function (uniformsList) {
  79093. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  79094. };
  79095. /**
  79096. * Returns color grading data based on a hue, density, saturation and exposure value.
  79097. * @param filterHue The hue of the color filter.
  79098. * @param filterDensity The density of the color filter.
  79099. * @param saturation The saturation.
  79100. * @param exposure The exposure.
  79101. * @param result The result data container.
  79102. */
  79103. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  79104. if (hue == null) {
  79105. return;
  79106. }
  79107. hue = ColorCurves.clamp(hue, 0, 360);
  79108. density = ColorCurves.clamp(density, -100, 100);
  79109. saturation = ColorCurves.clamp(saturation, -100, 100);
  79110. exposure = ColorCurves.clamp(exposure, -100, 100);
  79111. // Remap the slider/config filter density with non-linear mapping and also scale by half
  79112. // so that the maximum filter density is only 50% control. This provides fine control
  79113. // for small values and reasonable range.
  79114. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  79115. density *= 0.5;
  79116. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  79117. if (density < 0) {
  79118. density *= -1;
  79119. hue = (hue + 180) % 360;
  79120. }
  79121. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  79122. result.scaleToRef(2, result);
  79123. result.a = 1 + 0.01 * saturation;
  79124. };
  79125. /**
  79126. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  79127. * @param value The input slider value in range [-100,100].
  79128. * @returns Adjusted value.
  79129. */
  79130. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  79131. value /= 100;
  79132. var x = Math.abs(value);
  79133. x = Math.pow(x, 2);
  79134. if (value < 0) {
  79135. x *= -1;
  79136. }
  79137. x *= 100;
  79138. return x;
  79139. };
  79140. /**
  79141. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  79142. * @param hue The hue (H) input.
  79143. * @param saturation The saturation (S) input.
  79144. * @param brightness The brightness (B) input.
  79145. * @result An RGBA color represented as Vector4.
  79146. */
  79147. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  79148. var h = ColorCurves.clamp(hue, 0, 360);
  79149. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  79150. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  79151. if (s === 0) {
  79152. result.r = v;
  79153. result.g = v;
  79154. result.b = v;
  79155. }
  79156. else {
  79157. // sector 0 to 5
  79158. h /= 60;
  79159. var i = Math.floor(h);
  79160. // fractional part of h
  79161. var f = h - i;
  79162. var p = v * (1 - s);
  79163. var q = v * (1 - s * f);
  79164. var t = v * (1 - s * (1 - f));
  79165. switch (i) {
  79166. case 0:
  79167. result.r = v;
  79168. result.g = t;
  79169. result.b = p;
  79170. break;
  79171. case 1:
  79172. result.r = q;
  79173. result.g = v;
  79174. result.b = p;
  79175. break;
  79176. case 2:
  79177. result.r = p;
  79178. result.g = v;
  79179. result.b = t;
  79180. break;
  79181. case 3:
  79182. result.r = p;
  79183. result.g = q;
  79184. result.b = v;
  79185. break;
  79186. case 4:
  79187. result.r = t;
  79188. result.g = p;
  79189. result.b = v;
  79190. break;
  79191. default: // case 5:
  79192. result.r = v;
  79193. result.g = p;
  79194. result.b = q;
  79195. break;
  79196. }
  79197. }
  79198. result.a = 1;
  79199. };
  79200. /**
  79201. * Returns a value clamped between min and max
  79202. * @param value The value to clamp
  79203. * @param min The minimum of value
  79204. * @param max The maximum of value
  79205. * @returns The clamped value.
  79206. */
  79207. ColorCurves.clamp = function (value, min, max) {
  79208. return Math.min(Math.max(value, min), max);
  79209. };
  79210. /**
  79211. * Clones the current color curve instance.
  79212. * @return The cloned curves
  79213. */
  79214. ColorCurves.prototype.clone = function () {
  79215. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  79216. };
  79217. /**
  79218. * Serializes the current color curve instance to a json representation.
  79219. * @return a JSON representation
  79220. */
  79221. ColorCurves.prototype.serialize = function () {
  79222. return BABYLON.SerializationHelper.Serialize(this);
  79223. };
  79224. /**
  79225. * Parses the color curve from a json representation.
  79226. * @param source the JSON source to parse
  79227. * @return The parsed curves
  79228. */
  79229. ColorCurves.Parse = function (source) {
  79230. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  79231. };
  79232. __decorate([
  79233. BABYLON.serialize()
  79234. ], ColorCurves.prototype, "_globalHue", void 0);
  79235. __decorate([
  79236. BABYLON.serialize()
  79237. ], ColorCurves.prototype, "_globalDensity", void 0);
  79238. __decorate([
  79239. BABYLON.serialize()
  79240. ], ColorCurves.prototype, "_globalSaturation", void 0);
  79241. __decorate([
  79242. BABYLON.serialize()
  79243. ], ColorCurves.prototype, "_globalExposure", void 0);
  79244. __decorate([
  79245. BABYLON.serialize()
  79246. ], ColorCurves.prototype, "_highlightsHue", void 0);
  79247. __decorate([
  79248. BABYLON.serialize()
  79249. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  79250. __decorate([
  79251. BABYLON.serialize()
  79252. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  79253. __decorate([
  79254. BABYLON.serialize()
  79255. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  79256. __decorate([
  79257. BABYLON.serialize()
  79258. ], ColorCurves.prototype, "_midtonesHue", void 0);
  79259. __decorate([
  79260. BABYLON.serialize()
  79261. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  79262. __decorate([
  79263. BABYLON.serialize()
  79264. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  79265. __decorate([
  79266. BABYLON.serialize()
  79267. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  79268. return ColorCurves;
  79269. }());
  79270. BABYLON.ColorCurves = ColorCurves;
  79271. })(BABYLON || (BABYLON = {}));
  79272. //# sourceMappingURL=babylon.colorCurves.js.map
  79273. var BABYLON;
  79274. (function (BABYLON) {
  79275. var RefractionPostProcess = /** @class */ (function (_super) {
  79276. __extends(RefractionPostProcess, _super);
  79277. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  79278. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  79279. _this.color = color;
  79280. _this.depth = depth;
  79281. _this.colorLevel = colorLevel;
  79282. _this._ownRefractionTexture = true;
  79283. _this.onActivateObservable.add(function (cam) {
  79284. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  79285. });
  79286. _this.onApplyObservable.add(function (effect) {
  79287. effect.setColor3("baseColor", _this.color);
  79288. effect.setFloat("depth", _this.depth);
  79289. effect.setFloat("colorLevel", _this.colorLevel);
  79290. effect.setTexture("refractionSampler", _this._refTexture);
  79291. });
  79292. return _this;
  79293. }
  79294. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  79295. /**
  79296. * Gets or sets the refraction texture
  79297. * Please note that you are responsible for disposing the texture if you set it manually
  79298. */
  79299. get: function () {
  79300. return this._refTexture;
  79301. },
  79302. set: function (value) {
  79303. if (this._refTexture && this._ownRefractionTexture) {
  79304. this._refTexture.dispose();
  79305. }
  79306. this._refTexture = value;
  79307. this._ownRefractionTexture = false;
  79308. },
  79309. enumerable: true,
  79310. configurable: true
  79311. });
  79312. // Methods
  79313. RefractionPostProcess.prototype.dispose = function (camera) {
  79314. if (this._refTexture && this._ownRefractionTexture) {
  79315. this._refTexture.dispose();
  79316. this._refTexture = null;
  79317. }
  79318. _super.prototype.dispose.call(this, camera);
  79319. };
  79320. return RefractionPostProcess;
  79321. }(BABYLON.PostProcess));
  79322. BABYLON.RefractionPostProcess = RefractionPostProcess;
  79323. })(BABYLON || (BABYLON = {}));
  79324. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  79325. var BABYLON;
  79326. (function (BABYLON) {
  79327. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  79328. __extends(BlackAndWhitePostProcess, _super);
  79329. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  79330. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  79331. _this.degree = 1;
  79332. _this.onApplyObservable.add(function (effect) {
  79333. effect.setFloat("degree", _this.degree);
  79334. });
  79335. return _this;
  79336. }
  79337. return BlackAndWhitePostProcess;
  79338. }(BABYLON.PostProcess));
  79339. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  79340. })(BABYLON || (BABYLON = {}));
  79341. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  79342. var BABYLON;
  79343. (function (BABYLON) {
  79344. /**
  79345. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  79346. * input texture to perform effects such as edge detection or sharpening
  79347. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79348. */
  79349. var ConvolutionPostProcess = /** @class */ (function (_super) {
  79350. __extends(ConvolutionPostProcess, _super);
  79351. /**
  79352. * Creates a new instance ConvolutionPostProcess
  79353. * @param name The name of the effect.
  79354. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  79355. * @param options The required width/height ratio to downsize to before computing the render pass.
  79356. * @param camera The camera to apply the render pass to.
  79357. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79358. * @param engine The engine which the post process will be applied. (default: current engine)
  79359. * @param reusable If the post process can be reused on the same frame. (default: false)
  79360. * @param textureType Type of textures used when performing the post process. (default: 0)
  79361. */
  79362. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  79363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79364. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79365. _this.kernel = kernel;
  79366. _this.onApply = function (effect) {
  79367. effect.setFloat2("screenSize", _this.width, _this.height);
  79368. effect.setArray("kernel", _this.kernel);
  79369. };
  79370. return _this;
  79371. }
  79372. // Statics
  79373. /**
  79374. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79375. */
  79376. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  79377. /**
  79378. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79379. */
  79380. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  79381. /**
  79382. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79383. */
  79384. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  79385. /**
  79386. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79387. */
  79388. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  79389. /**
  79390. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79391. */
  79392. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  79393. /**
  79394. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79395. */
  79396. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  79397. return ConvolutionPostProcess;
  79398. }(BABYLON.PostProcess));
  79399. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  79400. })(BABYLON || (BABYLON = {}));
  79401. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  79402. var BABYLON;
  79403. (function (BABYLON) {
  79404. var FilterPostProcess = /** @class */ (function (_super) {
  79405. __extends(FilterPostProcess, _super);
  79406. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  79407. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  79408. _this.kernelMatrix = kernelMatrix;
  79409. _this.onApply = function (effect) {
  79410. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  79411. };
  79412. return _this;
  79413. }
  79414. return FilterPostProcess;
  79415. }(BABYLON.PostProcess));
  79416. BABYLON.FilterPostProcess = FilterPostProcess;
  79417. })(BABYLON || (BABYLON = {}));
  79418. //# sourceMappingURL=babylon.filterPostProcess.js.map
  79419. var BABYLON;
  79420. (function (BABYLON) {
  79421. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  79422. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  79423. __extends(VolumetricLightScatteringPostProcess, _super);
  79424. /**
  79425. * @constructor
  79426. * @param {string} name - The post-process name
  79427. * @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)
  79428. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  79429. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  79430. * @param {number} samples - The post-process quality, default 100
  79431. * @param {number} samplingMode - The post-process filtering mode
  79432. * @param {BABYLON.Engine} engine - The babylon engine
  79433. * @param {boolean} reusable - If the post-process is reusable
  79434. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  79435. */
  79436. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  79437. if (samples === void 0) { samples = 100; }
  79438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79439. 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;
  79440. _this._screenCoordinates = BABYLON.Vector2.Zero();
  79441. /**
  79442. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  79443. */
  79444. _this.customMeshPosition = BABYLON.Vector3.Zero();
  79445. /**
  79446. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  79447. */
  79448. _this.useCustomMeshPosition = false;
  79449. /**
  79450. * If the post-process should inverse the light scattering direction
  79451. */
  79452. _this.invert = true;
  79453. /**
  79454. * Array containing the excluded meshes not rendered in the internal pass
  79455. */
  79456. _this.excludedMeshes = new Array();
  79457. /**
  79458. * Controls the overall intensity of the post-process
  79459. */
  79460. _this.exposure = 0.3;
  79461. /**
  79462. * Dissipates each sample's contribution in range [0, 1]
  79463. */
  79464. _this.decay = 0.96815;
  79465. /**
  79466. * Controls the overall intensity of each sample
  79467. */
  79468. _this.weight = 0.58767;
  79469. /**
  79470. * Controls the density of each sample
  79471. */
  79472. _this.density = 0.926;
  79473. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  79474. engine = scene.getEngine();
  79475. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  79476. // Configure mesh
  79477. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  79478. // Configure
  79479. _this._createPass(scene, ratio.passRatio || ratio);
  79480. _this.onActivate = function (camera) {
  79481. if (!_this.isSupported) {
  79482. _this.dispose(camera);
  79483. }
  79484. _this.onActivate = null;
  79485. };
  79486. _this.onApplyObservable.add(function (effect) {
  79487. _this._updateMeshScreenCoordinates(scene);
  79488. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  79489. effect.setFloat("exposure", _this.exposure);
  79490. effect.setFloat("decay", _this.decay);
  79491. effect.setFloat("weight", _this.weight);
  79492. effect.setFloat("density", _this.density);
  79493. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  79494. });
  79495. return _this;
  79496. }
  79497. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  79498. get: function () {
  79499. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79500. return false;
  79501. },
  79502. set: function (useDiffuseColor) {
  79503. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79504. },
  79505. enumerable: true,
  79506. configurable: true
  79507. });
  79508. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  79509. return "VolumetricLightScatteringPostProcess";
  79510. };
  79511. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  79512. var mesh = subMesh.getMesh();
  79513. // Render this.mesh as default
  79514. if (mesh === this.mesh && mesh.material) {
  79515. return mesh.material.isReady(mesh);
  79516. }
  79517. var defines = [];
  79518. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79519. var material = subMesh.getMaterial();
  79520. // Alpha test
  79521. if (material) {
  79522. if (material.needAlphaTesting()) {
  79523. defines.push("#define ALPHATEST");
  79524. }
  79525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79526. attribs.push(BABYLON.VertexBuffer.UVKind);
  79527. defines.push("#define UV1");
  79528. }
  79529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79531. defines.push("#define UV2");
  79532. }
  79533. }
  79534. // Bones
  79535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79538. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79539. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79540. }
  79541. else {
  79542. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79543. }
  79544. // Instances
  79545. if (useInstances) {
  79546. defines.push("#define INSTANCES");
  79547. attribs.push("world0");
  79548. attribs.push("world1");
  79549. attribs.push("world2");
  79550. attribs.push("world3");
  79551. }
  79552. // Get correct effect
  79553. var join = defines.join("\n");
  79554. if (this._cachedDefines !== join) {
  79555. this._cachedDefines = join;
  79556. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  79557. }
  79558. return this._volumetricLightScatteringPass.isReady();
  79559. };
  79560. /**
  79561. * Sets the new light position for light scattering effect
  79562. * @param {BABYLON.Vector3} The new custom light position
  79563. */
  79564. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  79565. this.customMeshPosition = position;
  79566. };
  79567. /**
  79568. * Returns the light position for light scattering effect
  79569. * @return {BABYLON.Vector3} The custom light position
  79570. */
  79571. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  79572. return this.customMeshPosition;
  79573. };
  79574. /**
  79575. * Disposes the internal assets and detaches the post-process from the camera
  79576. */
  79577. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  79578. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  79579. if (rttIndex !== -1) {
  79580. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  79581. }
  79582. this._volumetricLightScatteringRTT.dispose();
  79583. _super.prototype.dispose.call(this, camera);
  79584. };
  79585. /**
  79586. * Returns the render target texture used by the post-process
  79587. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  79588. */
  79589. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  79590. return this._volumetricLightScatteringRTT;
  79591. };
  79592. // Private methods
  79593. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  79594. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  79595. return true;
  79596. }
  79597. return false;
  79598. };
  79599. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  79600. var _this = this;
  79601. var engine = scene.getEngine();
  79602. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79603. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79604. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79605. this._volumetricLightScatteringRTT.renderList = null;
  79606. this._volumetricLightScatteringRTT.renderParticles = false;
  79607. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  79608. var camera = this.getCamera();
  79609. if (camera) {
  79610. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79611. }
  79612. else {
  79613. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  79614. }
  79615. // Custom render function for submeshes
  79616. var renderSubMesh = function (subMesh) {
  79617. var mesh = subMesh.getRenderingMesh();
  79618. if (_this._meshExcluded(mesh)) {
  79619. return;
  79620. }
  79621. var material = subMesh.getMaterial();
  79622. if (!material) {
  79623. return;
  79624. }
  79625. var scene = mesh.getScene();
  79626. var engine = scene.getEngine();
  79627. // Culling
  79628. engine.setState(material.backFaceCulling);
  79629. // Managing instances
  79630. var batch = mesh._getInstancesRenderList(subMesh._id);
  79631. if (batch.mustReturn) {
  79632. return;
  79633. }
  79634. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79635. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  79636. var effect = _this._volumetricLightScatteringPass;
  79637. if (mesh === _this.mesh) {
  79638. if (subMesh.effect) {
  79639. effect = subMesh.effect;
  79640. }
  79641. else {
  79642. effect = material.getEffect();
  79643. }
  79644. }
  79645. engine.enableEffect(effect);
  79646. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  79647. if (mesh === _this.mesh) {
  79648. material.bind(mesh.getWorldMatrix(), mesh);
  79649. }
  79650. else {
  79651. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  79652. // Alpha test
  79653. if (material && material.needAlphaTesting()) {
  79654. var alphaTexture = material.getAlphaTestTexture();
  79655. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  79656. if (alphaTexture) {
  79657. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79658. }
  79659. }
  79660. // Bones
  79661. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79662. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79663. }
  79664. }
  79665. // Draw
  79666. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  79667. }
  79668. };
  79669. // Render target texture callbacks
  79670. var savedSceneClearColor;
  79671. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  79672. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  79673. savedSceneClearColor = scene.clearColor;
  79674. scene.clearColor = sceneClearColor;
  79675. });
  79676. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  79677. scene.clearColor = savedSceneClearColor;
  79678. });
  79679. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79680. var engine = scene.getEngine();
  79681. var index;
  79682. if (depthOnlySubMeshes.length) {
  79683. engine.setColorWrite(false);
  79684. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79685. renderSubMesh(depthOnlySubMeshes.data[index]);
  79686. }
  79687. engine.setColorWrite(true);
  79688. }
  79689. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79690. renderSubMesh(opaqueSubMeshes.data[index]);
  79691. }
  79692. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79693. renderSubMesh(alphaTestSubMeshes.data[index]);
  79694. }
  79695. if (transparentSubMeshes.length) {
  79696. // Sort sub meshes
  79697. for (index = 0; index < transparentSubMeshes.length; index++) {
  79698. var submesh = transparentSubMeshes.data[index];
  79699. var boundingInfo = submesh.getBoundingInfo();
  79700. if (boundingInfo && scene.activeCamera) {
  79701. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  79702. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  79703. }
  79704. }
  79705. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  79706. sortedArray.sort(function (a, b) {
  79707. // Alpha index first
  79708. if (a._alphaIndex > b._alphaIndex) {
  79709. return 1;
  79710. }
  79711. if (a._alphaIndex < b._alphaIndex) {
  79712. return -1;
  79713. }
  79714. // Then distance to camera
  79715. if (a._distanceToCamera < b._distanceToCamera) {
  79716. return 1;
  79717. }
  79718. if (a._distanceToCamera > b._distanceToCamera) {
  79719. return -1;
  79720. }
  79721. return 0;
  79722. });
  79723. // Render sub meshes
  79724. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  79725. for (index = 0; index < sortedArray.length; index++) {
  79726. renderSubMesh(sortedArray[index]);
  79727. }
  79728. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79729. }
  79730. };
  79731. };
  79732. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  79733. var transform = scene.getTransformMatrix();
  79734. var meshPosition;
  79735. if (this.useCustomMeshPosition) {
  79736. meshPosition = this.customMeshPosition;
  79737. }
  79738. else if (this.attachedNode) {
  79739. meshPosition = this.attachedNode.position;
  79740. }
  79741. else {
  79742. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  79743. }
  79744. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  79745. this._screenCoordinates.x = pos.x / this._viewPort.width;
  79746. this._screenCoordinates.y = pos.y / this._viewPort.height;
  79747. if (this.invert)
  79748. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  79749. };
  79750. // Static methods
  79751. /**
  79752. * Creates a default mesh for the Volumeric Light Scattering post-process
  79753. * @param {string} The mesh name
  79754. * @param {BABYLON.Scene} The scene where to create the mesh
  79755. * @return {BABYLON.Mesh} the default mesh
  79756. */
  79757. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  79758. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  79759. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  79760. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  79761. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  79762. mesh.material = material;
  79763. return mesh;
  79764. };
  79765. __decorate([
  79766. BABYLON.serializeAsVector3()
  79767. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  79768. __decorate([
  79769. BABYLON.serialize()
  79770. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  79771. __decorate([
  79772. BABYLON.serialize()
  79773. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  79774. __decorate([
  79775. BABYLON.serializeAsMeshReference()
  79776. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  79777. __decorate([
  79778. BABYLON.serialize()
  79779. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79780. __decorate([
  79781. BABYLON.serialize()
  79782. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79783. __decorate([
  79784. BABYLON.serialize()
  79785. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79786. __decorate([
  79787. BABYLON.serialize()
  79788. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79789. __decorate([
  79790. BABYLON.serialize()
  79791. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79792. return VolumetricLightScatteringPostProcess;
  79793. }(BABYLON.PostProcess));
  79794. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79795. })(BABYLON || (BABYLON = {}));
  79796. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79797. //
  79798. // This post-process allows the modification of rendered colors by using
  79799. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79800. //
  79801. // The object needs to be provided an url to a texture containing the color
  79802. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79803. // Use an image editing software to tweak the LUT to match your needs.
  79804. //
  79805. // For an example of a color LUT, see here:
  79806. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79807. // For explanations on color grading, see here:
  79808. // http://udn.epicgames.com/Three/ColorGrading.html
  79809. //
  79810. var BABYLON;
  79811. (function (BABYLON) {
  79812. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79813. __extends(ColorCorrectionPostProcess, _super);
  79814. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79815. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79816. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79817. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79818. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79819. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79820. _this.onApply = function (effect) {
  79821. effect.setTexture("colorTable", _this._colorTableTexture);
  79822. };
  79823. return _this;
  79824. }
  79825. return ColorCorrectionPostProcess;
  79826. }(BABYLON.PostProcess));
  79827. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79828. })(BABYLON || (BABYLON = {}));
  79829. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79830. var BABYLON;
  79831. (function (BABYLON) {
  79832. /** Defines operator used for tonemapping */
  79833. var TonemappingOperator;
  79834. (function (TonemappingOperator) {
  79835. /** Hable */
  79836. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79837. /** Reinhard */
  79838. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79839. /** HejiDawson */
  79840. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79841. /** Photographic */
  79842. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79843. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79844. ;
  79845. /**
  79846. * Defines a post process to apply tone mapping
  79847. */
  79848. var TonemapPostProcess = /** @class */ (function (_super) {
  79849. __extends(TonemapPostProcess, _super);
  79850. /**
  79851. * Creates a new TonemapPostProcess
  79852. * @param name defines the name of the postprocess
  79853. * @param _operator defines the operator to use
  79854. * @param exposureAdjustment defines the required exposure adjustement
  79855. * @param camera defines the camera to use (can be null)
  79856. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79857. * @param engine defines the hosting engine (can be ignore if camera is set)
  79858. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79859. */
  79860. function TonemapPostProcess(name, _operator,
  79861. /** Defines the required exposure adjustement */
  79862. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79864. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79865. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79866. _this._operator = _operator;
  79867. _this.exposureAdjustment = exposureAdjustment;
  79868. var defines = "#define ";
  79869. if (_this._operator === TonemappingOperator.Hable)
  79870. defines += "HABLE_TONEMAPPING";
  79871. else if (_this._operator === TonemappingOperator.Reinhard)
  79872. defines += "REINHARD_TONEMAPPING";
  79873. else if (_this._operator === TonemappingOperator.HejiDawson)
  79874. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79875. else if (_this._operator === TonemappingOperator.Photographic)
  79876. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79877. //sadly a second call to create the effect.
  79878. _this.updateEffect(defines);
  79879. _this.onApply = function (effect) {
  79880. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79881. };
  79882. return _this;
  79883. }
  79884. return TonemapPostProcess;
  79885. }(BABYLON.PostProcess));
  79886. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79887. })(BABYLON || (BABYLON = {}));
  79888. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79889. var BABYLON;
  79890. (function (BABYLON) {
  79891. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79892. __extends(DisplayPassPostProcess, _super);
  79893. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79894. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79895. }
  79896. return DisplayPassPostProcess;
  79897. }(BABYLON.PostProcess));
  79898. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79899. })(BABYLON || (BABYLON = {}));
  79900. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79901. var BABYLON;
  79902. (function (BABYLON) {
  79903. var HighlightsPostProcess = /** @class */ (function (_super) {
  79904. __extends(HighlightsPostProcess, _super);
  79905. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79906. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79907. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79908. }
  79909. return HighlightsPostProcess;
  79910. }(BABYLON.PostProcess));
  79911. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79912. })(BABYLON || (BABYLON = {}));
  79913. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79914. var BABYLON;
  79915. (function (BABYLON) {
  79916. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79917. __extends(ImageProcessingPostProcess, _super);
  79918. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79919. if (camera === void 0) { camera = null; }
  79920. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79921. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79922. _this._fromLinearSpace = true;
  79923. /**
  79924. * Defines cache preventing GC.
  79925. */
  79926. _this._defines = {
  79927. IMAGEPROCESSING: false,
  79928. VIGNETTE: false,
  79929. VIGNETTEBLENDMODEMULTIPLY: false,
  79930. VIGNETTEBLENDMODEOPAQUE: false,
  79931. TONEMAPPING: false,
  79932. CONTRAST: false,
  79933. COLORCURVES: false,
  79934. COLORGRADING: false,
  79935. COLORGRADING3D: false,
  79936. FROMLINEARSPACE: false,
  79937. SAMPLER3DGREENDEPTH: false,
  79938. SAMPLER3DBGRMAP: false,
  79939. IMAGEPROCESSINGPOSTPROCESS: false,
  79940. EXPOSURE: false,
  79941. };
  79942. // Setup the configuration as forced by the constructor. This would then not force the
  79943. // scene materials output in linear space and let untouched the default forward pass.
  79944. if (imageProcessingConfiguration) {
  79945. imageProcessingConfiguration.applyByPostProcess = true;
  79946. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79947. // This will cause the shader to be compiled
  79948. _this.fromLinearSpace = false;
  79949. }
  79950. // Setup the default processing configuration to the scene.
  79951. else {
  79952. _this._attachImageProcessingConfiguration(null, true);
  79953. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79954. }
  79955. _this.onApply = function (effect) {
  79956. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79957. };
  79958. return _this;
  79959. }
  79960. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79961. /**
  79962. * Gets the image processing configuration used either in this material.
  79963. */
  79964. get: function () {
  79965. return this._imageProcessingConfiguration;
  79966. },
  79967. /**
  79968. * Sets the Default image processing configuration used either in the this material.
  79969. *
  79970. * If sets to null, the scene one is in use.
  79971. */
  79972. set: function (value) {
  79973. this._attachImageProcessingConfiguration(value);
  79974. },
  79975. enumerable: true,
  79976. configurable: true
  79977. });
  79978. /**
  79979. * Attaches a new image processing configuration to the PBR Material.
  79980. * @param configuration
  79981. */
  79982. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79983. var _this = this;
  79984. if (doNotBuild === void 0) { doNotBuild = false; }
  79985. if (configuration === this._imageProcessingConfiguration) {
  79986. return;
  79987. }
  79988. // Detaches observer.
  79989. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79990. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79991. }
  79992. // Pick the scene configuration if needed.
  79993. if (!configuration) {
  79994. var scene = null;
  79995. var engine = this.getEngine();
  79996. var camera = this.getCamera();
  79997. if (camera) {
  79998. scene = camera.getScene();
  79999. }
  80000. else if (engine && engine.scenes) {
  80001. var scenes = engine.scenes;
  80002. scene = scenes[scenes.length - 1];
  80003. }
  80004. else {
  80005. scene = BABYLON.Engine.LastCreatedScene;
  80006. }
  80007. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80008. }
  80009. else {
  80010. this._imageProcessingConfiguration = configuration;
  80011. }
  80012. // Attaches observer.
  80013. if (this._imageProcessingConfiguration) {
  80014. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80015. _this._updateParameters();
  80016. });
  80017. }
  80018. // Ensure the effect will be rebuilt.
  80019. if (!doNotBuild) {
  80020. this._updateParameters();
  80021. }
  80022. };
  80023. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80024. /**
  80025. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80026. */
  80027. get: function () {
  80028. return this.imageProcessingConfiguration.colorCurves;
  80029. },
  80030. /**
  80031. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80032. */
  80033. set: function (value) {
  80034. this.imageProcessingConfiguration.colorCurves = value;
  80035. },
  80036. enumerable: true,
  80037. configurable: true
  80038. });
  80039. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80040. /**
  80041. * Gets wether the color curves effect is enabled.
  80042. */
  80043. get: function () {
  80044. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80045. },
  80046. /**
  80047. * Sets wether the color curves effect is enabled.
  80048. */
  80049. set: function (value) {
  80050. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80051. },
  80052. enumerable: true,
  80053. configurable: true
  80054. });
  80055. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80056. /**
  80057. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80058. */
  80059. get: function () {
  80060. return this.imageProcessingConfiguration.colorGradingTexture;
  80061. },
  80062. /**
  80063. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80064. */
  80065. set: function (value) {
  80066. this.imageProcessingConfiguration.colorGradingTexture = value;
  80067. },
  80068. enumerable: true,
  80069. configurable: true
  80070. });
  80071. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80072. /**
  80073. * Gets wether the color grading effect is enabled.
  80074. */
  80075. get: function () {
  80076. return this.imageProcessingConfiguration.colorGradingEnabled;
  80077. },
  80078. /**
  80079. * Gets wether the color grading effect is enabled.
  80080. */
  80081. set: function (value) {
  80082. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80083. },
  80084. enumerable: true,
  80085. configurable: true
  80086. });
  80087. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  80088. /**
  80089. * Gets exposure used in the effect.
  80090. */
  80091. get: function () {
  80092. return this.imageProcessingConfiguration.exposure;
  80093. },
  80094. /**
  80095. * Sets exposure used in the effect.
  80096. */
  80097. set: function (value) {
  80098. this.imageProcessingConfiguration.exposure = value;
  80099. },
  80100. enumerable: true,
  80101. configurable: true
  80102. });
  80103. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  80104. /**
  80105. * Gets wether tonemapping is enabled or not.
  80106. */
  80107. get: function () {
  80108. return this._imageProcessingConfiguration.toneMappingEnabled;
  80109. },
  80110. /**
  80111. * Sets wether tonemapping is enabled or not
  80112. */
  80113. set: function (value) {
  80114. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80115. },
  80116. enumerable: true,
  80117. configurable: true
  80118. });
  80119. ;
  80120. ;
  80121. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  80122. /**
  80123. * Gets contrast used in the effect.
  80124. */
  80125. get: function () {
  80126. return this.imageProcessingConfiguration.contrast;
  80127. },
  80128. /**
  80129. * Sets contrast used in the effect.
  80130. */
  80131. set: function (value) {
  80132. this.imageProcessingConfiguration.contrast = value;
  80133. },
  80134. enumerable: true,
  80135. configurable: true
  80136. });
  80137. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  80138. /**
  80139. * Gets Vignette stretch size.
  80140. */
  80141. get: function () {
  80142. return this.imageProcessingConfiguration.vignetteStretch;
  80143. },
  80144. /**
  80145. * Sets Vignette stretch size.
  80146. */
  80147. set: function (value) {
  80148. this.imageProcessingConfiguration.vignetteStretch = value;
  80149. },
  80150. enumerable: true,
  80151. configurable: true
  80152. });
  80153. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  80154. /**
  80155. * Gets Vignette centre X Offset.
  80156. */
  80157. get: function () {
  80158. return this.imageProcessingConfiguration.vignetteCentreX;
  80159. },
  80160. /**
  80161. * Sets Vignette centre X Offset.
  80162. */
  80163. set: function (value) {
  80164. this.imageProcessingConfiguration.vignetteCentreX = value;
  80165. },
  80166. enumerable: true,
  80167. configurable: true
  80168. });
  80169. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  80170. /**
  80171. * Gets Vignette centre Y Offset.
  80172. */
  80173. get: function () {
  80174. return this.imageProcessingConfiguration.vignetteCentreY;
  80175. },
  80176. /**
  80177. * Sets Vignette centre Y Offset.
  80178. */
  80179. set: function (value) {
  80180. this.imageProcessingConfiguration.vignetteCentreY = value;
  80181. },
  80182. enumerable: true,
  80183. configurable: true
  80184. });
  80185. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  80186. /**
  80187. * Gets Vignette weight or intensity of the vignette effect.
  80188. */
  80189. get: function () {
  80190. return this.imageProcessingConfiguration.vignetteWeight;
  80191. },
  80192. /**
  80193. * Sets Vignette weight or intensity of the vignette effect.
  80194. */
  80195. set: function (value) {
  80196. this.imageProcessingConfiguration.vignetteWeight = value;
  80197. },
  80198. enumerable: true,
  80199. configurable: true
  80200. });
  80201. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  80202. /**
  80203. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80204. * if vignetteEnabled is set to true.
  80205. */
  80206. get: function () {
  80207. return this.imageProcessingConfiguration.vignetteColor;
  80208. },
  80209. /**
  80210. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80211. * if vignetteEnabled is set to true.
  80212. */
  80213. set: function (value) {
  80214. this.imageProcessingConfiguration.vignetteColor = value;
  80215. },
  80216. enumerable: true,
  80217. configurable: true
  80218. });
  80219. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  80220. /**
  80221. * Gets Camera field of view used by the Vignette effect.
  80222. */
  80223. get: function () {
  80224. return this.imageProcessingConfiguration.vignetteCameraFov;
  80225. },
  80226. /**
  80227. * Sets Camera field of view used by the Vignette effect.
  80228. */
  80229. set: function (value) {
  80230. this.imageProcessingConfiguration.vignetteCameraFov = value;
  80231. },
  80232. enumerable: true,
  80233. configurable: true
  80234. });
  80235. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  80236. /**
  80237. * Gets the vignette blend mode allowing different kind of effect.
  80238. */
  80239. get: function () {
  80240. return this.imageProcessingConfiguration.vignetteBlendMode;
  80241. },
  80242. /**
  80243. * Sets the vignette blend mode allowing different kind of effect.
  80244. */
  80245. set: function (value) {
  80246. this.imageProcessingConfiguration.vignetteBlendMode = value;
  80247. },
  80248. enumerable: true,
  80249. configurable: true
  80250. });
  80251. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  80252. /**
  80253. * Gets wether the vignette effect is enabled.
  80254. */
  80255. get: function () {
  80256. return this.imageProcessingConfiguration.vignetteEnabled;
  80257. },
  80258. /**
  80259. * Sets wether the vignette effect is enabled.
  80260. */
  80261. set: function (value) {
  80262. this.imageProcessingConfiguration.vignetteEnabled = value;
  80263. },
  80264. enumerable: true,
  80265. configurable: true
  80266. });
  80267. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  80268. /**
  80269. * Gets wether the input of the processing is in Gamma or Linear Space.
  80270. */
  80271. get: function () {
  80272. return this._fromLinearSpace;
  80273. },
  80274. /**
  80275. * Sets wether the input of the processing is in Gamma or Linear Space.
  80276. */
  80277. set: function (value) {
  80278. if (this._fromLinearSpace === value) {
  80279. return;
  80280. }
  80281. this._fromLinearSpace = value;
  80282. this._updateParameters();
  80283. },
  80284. enumerable: true,
  80285. configurable: true
  80286. });
  80287. ImageProcessingPostProcess.prototype.getClassName = function () {
  80288. return "ImageProcessingPostProcess";
  80289. };
  80290. ImageProcessingPostProcess.prototype._updateParameters = function () {
  80291. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  80292. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  80293. var defines = "";
  80294. for (var define in this._defines) {
  80295. if (this._defines[define]) {
  80296. defines += "#define " + define + ";\r\n";
  80297. }
  80298. }
  80299. var samplers = ["textureSampler"];
  80300. var uniforms = ["scale"];
  80301. if (BABYLON.ImageProcessingConfiguration) {
  80302. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  80303. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  80304. }
  80305. this.updateEffect(defines, uniforms, samplers);
  80306. };
  80307. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  80308. _super.prototype.dispose.call(this, camera);
  80309. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80310. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80311. }
  80312. if (this._imageProcessingConfiguration) {
  80313. this.imageProcessingConfiguration.applyByPostProcess = false;
  80314. }
  80315. };
  80316. __decorate([
  80317. BABYLON.serialize()
  80318. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  80319. return ImageProcessingPostProcess;
  80320. }(BABYLON.PostProcess));
  80321. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  80322. })(BABYLON || (BABYLON = {}));
  80323. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  80324. var BABYLON;
  80325. (function (BABYLON) {
  80326. /**
  80327. * Class used to store bone information
  80328. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80329. */
  80330. var Bone = /** @class */ (function (_super) {
  80331. __extends(Bone, _super);
  80332. /**
  80333. * Create a new bone
  80334. * @param name defines the bone name
  80335. * @param skeleton defines the parent skeleton
  80336. * @param parentBone defines the parent (can be null if the bone is the root)
  80337. * @param localMatrix defines the local matrix
  80338. * @param restPose defines the rest pose matrix
  80339. * @param baseMatrix defines the base matrix
  80340. * @param index defines index of the bone in the hiearchy
  80341. */
  80342. function Bone(
  80343. /**
  80344. * defines the bone name
  80345. */
  80346. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  80347. if (parentBone === void 0) { parentBone = null; }
  80348. if (localMatrix === void 0) { localMatrix = null; }
  80349. if (restPose === void 0) { restPose = null; }
  80350. if (baseMatrix === void 0) { baseMatrix = null; }
  80351. if (index === void 0) { index = null; }
  80352. var _this = _super.call(this, name, skeleton.getScene()) || this;
  80353. _this.name = name;
  80354. /**
  80355. * Gets the list of child bones
  80356. */
  80357. _this.children = new Array();
  80358. /** Gets the animations associated with this bone */
  80359. _this.animations = new Array();
  80360. /**
  80361. * @hidden Internal only
  80362. * Set this value to map this bone to a different index in the transform matrices
  80363. * Set this value to -1 to exclude the bone from the transform matrices
  80364. */
  80365. _this._index = null;
  80366. _this._absoluteTransform = new BABYLON.Matrix();
  80367. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  80368. _this._scalingDeterminant = 1;
  80369. _this._worldTransform = new BABYLON.Matrix();
  80370. _this._needToDecompose = true;
  80371. _this._needToCompose = false;
  80372. _this._skeleton = skeleton;
  80373. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  80374. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  80375. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  80376. _this._index = index;
  80377. skeleton.bones.push(_this);
  80378. _this.setParent(parentBone, false);
  80379. if (baseMatrix || localMatrix) {
  80380. _this._updateDifferenceMatrix();
  80381. }
  80382. return _this;
  80383. }
  80384. Object.defineProperty(Bone.prototype, "_matrix", {
  80385. /** @hidden */
  80386. get: function () {
  80387. this._compose();
  80388. return this._localMatrix;
  80389. },
  80390. /** @hidden */
  80391. set: function (value) {
  80392. this._localMatrix.copyFrom(value);
  80393. this._needToDecompose = true;
  80394. },
  80395. enumerable: true,
  80396. configurable: true
  80397. });
  80398. // Members
  80399. /**
  80400. * Gets the parent skeleton
  80401. * @returns a skeleton
  80402. */
  80403. Bone.prototype.getSkeleton = function () {
  80404. return this._skeleton;
  80405. };
  80406. /**
  80407. * Gets parent bone
  80408. * @returns a bone or null if the bone is the root of the bone hierarchy
  80409. */
  80410. Bone.prototype.getParent = function () {
  80411. return this._parent;
  80412. };
  80413. /**
  80414. * Sets the parent bone
  80415. * @param parent defines the parent (can be null if the bone is the root)
  80416. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80417. */
  80418. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  80419. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80420. if (this._parent === parent) {
  80421. return;
  80422. }
  80423. if (this._parent) {
  80424. var index = this._parent.children.indexOf(this);
  80425. if (index !== -1) {
  80426. this._parent.children.splice(index, 1);
  80427. }
  80428. }
  80429. this._parent = parent;
  80430. if (this._parent) {
  80431. this._parent.children.push(this);
  80432. }
  80433. if (updateDifferenceMatrix) {
  80434. this._updateDifferenceMatrix();
  80435. }
  80436. this.markAsDirty();
  80437. };
  80438. /**
  80439. * Gets the local matrix
  80440. * @returns a matrix
  80441. */
  80442. Bone.prototype.getLocalMatrix = function () {
  80443. this._compose();
  80444. return this._localMatrix;
  80445. };
  80446. /**
  80447. * Gets the base matrix (initial matrix which remains unchanged)
  80448. * @returns a matrix
  80449. */
  80450. Bone.prototype.getBaseMatrix = function () {
  80451. return this._baseMatrix;
  80452. };
  80453. /**
  80454. * Gets the rest pose matrix
  80455. * @returns a matrix
  80456. */
  80457. Bone.prototype.getRestPose = function () {
  80458. return this._restPose;
  80459. };
  80460. /**
  80461. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  80462. */
  80463. Bone.prototype.getWorldMatrix = function () {
  80464. return this._worldTransform;
  80465. };
  80466. /**
  80467. * Sets the local matrix to rest pose matrix
  80468. */
  80469. Bone.prototype.returnToRest = function () {
  80470. this.updateMatrix(this._restPose.clone());
  80471. };
  80472. /**
  80473. * Gets the inverse of the absolute transform matrix.
  80474. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  80475. * @returns a matrix
  80476. */
  80477. Bone.prototype.getInvertedAbsoluteTransform = function () {
  80478. return this._invertedAbsoluteTransform;
  80479. };
  80480. /**
  80481. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  80482. * @returns a matrix
  80483. */
  80484. Bone.prototype.getAbsoluteTransform = function () {
  80485. return this._absoluteTransform;
  80486. };
  80487. Object.defineProperty(Bone.prototype, "position", {
  80488. // Properties (matches AbstractMesh properties)
  80489. /** Gets or sets current position (in local space) */
  80490. get: function () {
  80491. this._decompose();
  80492. return this._localPosition;
  80493. },
  80494. set: function (newPosition) {
  80495. this._decompose();
  80496. this._localPosition.copyFrom(newPosition);
  80497. this._markAsDirtyAndCompose();
  80498. },
  80499. enumerable: true,
  80500. configurable: true
  80501. });
  80502. Object.defineProperty(Bone.prototype, "rotation", {
  80503. /** Gets or sets current rotation (in local space) */
  80504. get: function () {
  80505. return this.getRotation();
  80506. },
  80507. set: function (newRotation) {
  80508. this.setRotation(newRotation);
  80509. },
  80510. enumerable: true,
  80511. configurable: true
  80512. });
  80513. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  80514. /** Gets or sets current rotation quaternion (in local space) */
  80515. get: function () {
  80516. this._decompose();
  80517. return this._localRotation;
  80518. },
  80519. set: function (newRotation) {
  80520. this.setRotationQuaternion(newRotation);
  80521. },
  80522. enumerable: true,
  80523. configurable: true
  80524. });
  80525. Object.defineProperty(Bone.prototype, "scaling", {
  80526. /** Gets or sets current scaling (in local space) */
  80527. get: function () {
  80528. return this.getScale();
  80529. },
  80530. set: function (newScaling) {
  80531. this.setScale(newScaling);
  80532. },
  80533. enumerable: true,
  80534. configurable: true
  80535. });
  80536. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  80537. /**
  80538. * Gets the animation properties override
  80539. */
  80540. get: function () {
  80541. return this._skeleton.animationPropertiesOverride;
  80542. },
  80543. enumerable: true,
  80544. configurable: true
  80545. });
  80546. // Methods
  80547. Bone.prototype._decompose = function () {
  80548. if (!this._needToDecompose) {
  80549. return;
  80550. }
  80551. this._needToDecompose = false;
  80552. if (!this._localScaling) {
  80553. this._localScaling = BABYLON.Vector3.Zero();
  80554. this._localRotation = BABYLON.Quaternion.Zero();
  80555. this._localPosition = BABYLON.Vector3.Zero();
  80556. }
  80557. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  80558. };
  80559. Bone.prototype._compose = function () {
  80560. if (!this._needToCompose) {
  80561. return;
  80562. }
  80563. this._needToCompose = false;
  80564. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  80565. };
  80566. /**
  80567. * Update the base and local matrices
  80568. * @param matrix defines the new base or local matrix
  80569. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80570. * @param updateLocalMatrix defines if the local matrix should be updated
  80571. */
  80572. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  80573. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80574. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  80575. this._baseMatrix.copyFrom(matrix);
  80576. if (updateDifferenceMatrix) {
  80577. this._updateDifferenceMatrix();
  80578. }
  80579. if (updateLocalMatrix) {
  80580. this._localMatrix.copyFrom(matrix);
  80581. this._markAsDirtyAndDecompose();
  80582. }
  80583. else {
  80584. this.markAsDirty();
  80585. }
  80586. };
  80587. /** @hidden */
  80588. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  80589. if (updateChildren === void 0) { updateChildren = true; }
  80590. if (!rootMatrix) {
  80591. rootMatrix = this._baseMatrix;
  80592. }
  80593. if (this._parent) {
  80594. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80595. }
  80596. else {
  80597. this._absoluteTransform.copyFrom(rootMatrix);
  80598. }
  80599. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  80600. if (updateChildren) {
  80601. for (var index = 0; index < this.children.length; index++) {
  80602. this.children[index]._updateDifferenceMatrix();
  80603. }
  80604. }
  80605. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  80606. };
  80607. /**
  80608. * Flag the bone as dirty (Forcing it to update everything)
  80609. */
  80610. Bone.prototype.markAsDirty = function () {
  80611. this._currentRenderId++;
  80612. this._childRenderId++;
  80613. this._skeleton._markAsDirty();
  80614. };
  80615. Bone.prototype._markAsDirtyAndCompose = function () {
  80616. this.markAsDirty();
  80617. this._needToCompose = true;
  80618. };
  80619. Bone.prototype._markAsDirtyAndDecompose = function () {
  80620. this.markAsDirty();
  80621. this._needToDecompose = true;
  80622. };
  80623. /**
  80624. * Copy an animation range from another bone
  80625. * @param source defines the source bone
  80626. * @param rangeName defines the range name to copy
  80627. * @param frameOffset defines the frame offset
  80628. * @param rescaleAsRequired defines if rescaling must be applied if required
  80629. * @param skelDimensionsRatio defines the scaling ratio
  80630. * @returns true if operation was successful
  80631. */
  80632. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  80633. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80634. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  80635. // all animation may be coming from a library skeleton, so may need to create animation
  80636. if (this.animations.length === 0) {
  80637. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  80638. this.animations[0].setKeys([]);
  80639. }
  80640. // get animation info / verify there is such a range from the source bone
  80641. var sourceRange = source.animations[0].getRange(rangeName);
  80642. if (!sourceRange) {
  80643. return false;
  80644. }
  80645. var from = sourceRange.from;
  80646. var to = sourceRange.to;
  80647. var sourceKeys = source.animations[0].getKeys();
  80648. // rescaling prep
  80649. var sourceBoneLength = source.length;
  80650. var sourceParent = source.getParent();
  80651. var parent = this.getParent();
  80652. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  80653. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  80654. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  80655. var destKeys = this.animations[0].getKeys();
  80656. // loop vars declaration
  80657. var orig;
  80658. var origTranslation;
  80659. var mat;
  80660. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  80661. orig = sourceKeys[key];
  80662. if (orig.frame >= from && orig.frame <= to) {
  80663. if (rescaleAsRequired) {
  80664. mat = orig.value.clone();
  80665. // scale based on parent ratio, when bone has parent
  80666. if (parentScalingReqd) {
  80667. origTranslation = mat.getTranslation();
  80668. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  80669. // scale based on skeleton dimension ratio when root bone, and value is passed
  80670. }
  80671. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  80672. origTranslation = mat.getTranslation();
  80673. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  80674. // use original when root bone, and no data for skelDimensionsRatio
  80675. }
  80676. else {
  80677. mat = orig.value;
  80678. }
  80679. }
  80680. else {
  80681. mat = orig.value;
  80682. }
  80683. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  80684. }
  80685. }
  80686. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  80687. return true;
  80688. };
  80689. /**
  80690. * Translate the bone in local or world space
  80691. * @param vec The amount to translate the bone
  80692. * @param space The space that the translation is in
  80693. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80694. */
  80695. Bone.prototype.translate = function (vec, space, mesh) {
  80696. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80697. var lm = this.getLocalMatrix();
  80698. if (space == BABYLON.Space.LOCAL) {
  80699. lm.m[12] += vec.x;
  80700. lm.m[13] += vec.y;
  80701. lm.m[14] += vec.z;
  80702. }
  80703. else {
  80704. var wm = null;
  80705. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80706. if (mesh) {
  80707. wm = mesh.getWorldMatrix();
  80708. }
  80709. this._skeleton.computeAbsoluteTransforms();
  80710. var tmat = Bone._tmpMats[0];
  80711. var tvec = Bone._tmpVecs[0];
  80712. if (this._parent) {
  80713. if (mesh && wm) {
  80714. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80715. tmat.multiplyToRef(wm, tmat);
  80716. }
  80717. else {
  80718. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80719. }
  80720. }
  80721. tmat.m[12] = 0;
  80722. tmat.m[13] = 0;
  80723. tmat.m[14] = 0;
  80724. tmat.invert();
  80725. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  80726. lm.m[12] += tvec.x;
  80727. lm.m[13] += tvec.y;
  80728. lm.m[14] += tvec.z;
  80729. }
  80730. this._markAsDirtyAndDecompose();
  80731. };
  80732. /**
  80733. * Set the postion of the bone in local or world space
  80734. * @param position The position to set the bone
  80735. * @param space The space that the position is in
  80736. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80737. */
  80738. Bone.prototype.setPosition = function (position, space, mesh) {
  80739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80740. var lm = this.getLocalMatrix();
  80741. if (space == BABYLON.Space.LOCAL) {
  80742. lm.m[12] = position.x;
  80743. lm.m[13] = position.y;
  80744. lm.m[14] = position.z;
  80745. }
  80746. else {
  80747. var wm = null;
  80748. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80749. if (mesh) {
  80750. wm = mesh.getWorldMatrix();
  80751. }
  80752. this._skeleton.computeAbsoluteTransforms();
  80753. var tmat = Bone._tmpMats[0];
  80754. var vec = Bone._tmpVecs[0];
  80755. if (this._parent) {
  80756. if (mesh && wm) {
  80757. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80758. tmat.multiplyToRef(wm, tmat);
  80759. }
  80760. else {
  80761. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80762. }
  80763. }
  80764. tmat.invert();
  80765. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  80766. lm.m[12] = vec.x;
  80767. lm.m[13] = vec.y;
  80768. lm.m[14] = vec.z;
  80769. }
  80770. this._markAsDirtyAndDecompose();
  80771. };
  80772. /**
  80773. * Set the absolute position of the bone (world space)
  80774. * @param position The position to set the bone
  80775. * @param mesh The mesh that this bone is attached to
  80776. */
  80777. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80778. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80779. };
  80780. /**
  80781. * Scale the bone on the x, y and z axes (in local space)
  80782. * @param x The amount to scale the bone on the x axis
  80783. * @param y The amount to scale the bone on the y axis
  80784. * @param z The amount to scale the bone on the z axis
  80785. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80786. */
  80787. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80788. if (scaleChildren === void 0) { scaleChildren = false; }
  80789. var locMat = this.getLocalMatrix();
  80790. // Apply new scaling on top of current local matrix
  80791. var scaleMat = Bone._tmpMats[0];
  80792. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80793. scaleMat.multiplyToRef(locMat, locMat);
  80794. // Invert scaling matrix and apply the inverse to all children
  80795. scaleMat.invert();
  80796. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80797. var child = _a[_i];
  80798. var cm = child.getLocalMatrix();
  80799. cm.multiplyToRef(scaleMat, cm);
  80800. cm.m[12] *= x;
  80801. cm.m[13] *= y;
  80802. cm.m[14] *= z;
  80803. child._markAsDirtyAndDecompose();
  80804. }
  80805. this._markAsDirtyAndDecompose();
  80806. if (scaleChildren) {
  80807. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80808. var child = _c[_b];
  80809. child.scale(x, y, z, scaleChildren);
  80810. }
  80811. }
  80812. };
  80813. /**
  80814. * Set the bone scaling in local space
  80815. * @param scale defines the scaling vector
  80816. */
  80817. Bone.prototype.setScale = function (scale) {
  80818. this._decompose();
  80819. this._localScaling.copyFrom(scale);
  80820. this._markAsDirtyAndCompose();
  80821. };
  80822. /**
  80823. * Gets the current scaling in local space
  80824. * @returns the current scaling vector
  80825. */
  80826. Bone.prototype.getScale = function () {
  80827. this._decompose();
  80828. return this._localScaling;
  80829. };
  80830. /**
  80831. * Gets the current scaling in local space and stores it in a target vector
  80832. * @param result defines the target vector
  80833. */
  80834. Bone.prototype.getScaleToRef = function (result) {
  80835. this._decompose();
  80836. result.copyFrom(this._localScaling);
  80837. };
  80838. /**
  80839. * Set the yaw, pitch, and roll of the bone in local or world space
  80840. * @param yaw The rotation of the bone on the y axis
  80841. * @param pitch The rotation of the bone on the x axis
  80842. * @param roll The rotation of the bone on the z axis
  80843. * @param space The space that the axes of rotation are in
  80844. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80845. */
  80846. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80847. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80848. if (space === BABYLON.Space.LOCAL) {
  80849. var quat = Bone._tmpQuat;
  80850. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80851. this.setRotationQuaternion(quat, space, mesh);
  80852. return;
  80853. }
  80854. var rotMatInv = Bone._tmpMats[0];
  80855. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80856. return;
  80857. }
  80858. var rotMat = Bone._tmpMats[1];
  80859. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80860. rotMatInv.multiplyToRef(rotMat, rotMat);
  80861. this._rotateWithMatrix(rotMat, space, mesh);
  80862. };
  80863. /**
  80864. * Add a rotation to the bone on an axis in local or world space
  80865. * @param axis The axis to rotate the bone on
  80866. * @param amount The amount to rotate the bone
  80867. * @param space The space that the axis is in
  80868. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80869. */
  80870. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80871. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80872. var rmat = Bone._tmpMats[0];
  80873. rmat.m[12] = 0;
  80874. rmat.m[13] = 0;
  80875. rmat.m[14] = 0;
  80876. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80877. this._rotateWithMatrix(rmat, space, mesh);
  80878. };
  80879. /**
  80880. * Set the rotation of the bone to a particular axis angle in local or world space
  80881. * @param axis The axis to rotate the bone on
  80882. * @param angle The angle that the bone should be rotated to
  80883. * @param space The space that the axis is in
  80884. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80885. */
  80886. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80888. if (space === BABYLON.Space.LOCAL) {
  80889. var quat = Bone._tmpQuat;
  80890. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80891. this.setRotationQuaternion(quat, space, mesh);
  80892. return;
  80893. }
  80894. var rotMatInv = Bone._tmpMats[0];
  80895. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80896. return;
  80897. }
  80898. var rotMat = Bone._tmpMats[1];
  80899. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80900. rotMatInv.multiplyToRef(rotMat, rotMat);
  80901. this._rotateWithMatrix(rotMat, space, mesh);
  80902. };
  80903. /**
  80904. * Set the euler rotation of the bone in local of world space
  80905. * @param rotation The euler rotation that the bone should be set to
  80906. * @param space The space that the rotation is in
  80907. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80908. */
  80909. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80911. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80912. };
  80913. /**
  80914. * Set the quaternion rotation of the bone in local of world space
  80915. * @param quat The quaternion rotation that the bone should be set to
  80916. * @param space The space that the rotation is in
  80917. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80918. */
  80919. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80921. if (space === BABYLON.Space.LOCAL) {
  80922. this._decompose();
  80923. this._localRotation.copyFrom(quat);
  80924. this._markAsDirtyAndCompose();
  80925. return;
  80926. }
  80927. var rotMatInv = Bone._tmpMats[0];
  80928. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80929. return;
  80930. }
  80931. var rotMat = Bone._tmpMats[1];
  80932. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80933. rotMatInv.multiplyToRef(rotMat, rotMat);
  80934. this._rotateWithMatrix(rotMat, space, mesh);
  80935. };
  80936. /**
  80937. * Set the rotation matrix of the bone in local of world space
  80938. * @param rotMat The rotation matrix that the bone should be set to
  80939. * @param space The space that the rotation is in
  80940. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80941. */
  80942. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80944. if (space === BABYLON.Space.LOCAL) {
  80945. var quat = Bone._tmpQuat;
  80946. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80947. this.setRotationQuaternion(quat, space, mesh);
  80948. return;
  80949. }
  80950. var rotMatInv = Bone._tmpMats[0];
  80951. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80952. return;
  80953. }
  80954. var rotMat2 = Bone._tmpMats[1];
  80955. rotMat2.copyFrom(rotMat);
  80956. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80957. this._rotateWithMatrix(rotMat2, space, mesh);
  80958. };
  80959. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80961. var lmat = this.getLocalMatrix();
  80962. var lx = lmat.m[12];
  80963. var ly = lmat.m[13];
  80964. var lz = lmat.m[14];
  80965. var parent = this.getParent();
  80966. var parentScale = Bone._tmpMats[3];
  80967. var parentScaleInv = Bone._tmpMats[4];
  80968. if (parent && space == BABYLON.Space.WORLD) {
  80969. if (mesh) {
  80970. parentScale.copyFrom(mesh.getWorldMatrix());
  80971. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80972. }
  80973. else {
  80974. parentScale.copyFrom(parent.getAbsoluteTransform());
  80975. }
  80976. parentScaleInv.copyFrom(parentScale);
  80977. parentScaleInv.invert();
  80978. lmat.multiplyToRef(parentScale, lmat);
  80979. lmat.multiplyToRef(rmat, lmat);
  80980. lmat.multiplyToRef(parentScaleInv, lmat);
  80981. }
  80982. else {
  80983. if (space == BABYLON.Space.WORLD && mesh) {
  80984. parentScale.copyFrom(mesh.getWorldMatrix());
  80985. parentScaleInv.copyFrom(parentScale);
  80986. parentScaleInv.invert();
  80987. lmat.multiplyToRef(parentScale, lmat);
  80988. lmat.multiplyToRef(rmat, lmat);
  80989. lmat.multiplyToRef(parentScaleInv, lmat);
  80990. }
  80991. else {
  80992. lmat.multiplyToRef(rmat, lmat);
  80993. }
  80994. }
  80995. lmat.m[12] = lx;
  80996. lmat.m[13] = ly;
  80997. lmat.m[14] = lz;
  80998. this.computeAbsoluteTransforms();
  80999. this._markAsDirtyAndDecompose();
  81000. };
  81001. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81002. var scaleMatrix = Bone._tmpMats[2];
  81003. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81004. if (mesh) {
  81005. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81006. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81007. }
  81008. rotMatInv.invert();
  81009. if (isNaN(rotMatInv.m[0])) {
  81010. // Matrix failed to invert.
  81011. // This can happen if scale is zero for example.
  81012. return false;
  81013. }
  81014. scaleMatrix.m[0] *= this._scalingDeterminant;
  81015. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81016. return true;
  81017. };
  81018. /**
  81019. * Get the position of the bone in local or world space
  81020. * @param space The space that the returned position is in
  81021. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81022. * @returns The position of the bone
  81023. */
  81024. Bone.prototype.getPosition = function (space, mesh) {
  81025. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81026. if (mesh === void 0) { mesh = null; }
  81027. var pos = BABYLON.Vector3.Zero();
  81028. this.getPositionToRef(space, mesh, pos);
  81029. return pos;
  81030. };
  81031. /**
  81032. * Copy the position of the bone to a vector3 in local or world space
  81033. * @param space The space that the returned position is in
  81034. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81035. * @param result The vector3 to copy the position to
  81036. */
  81037. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81038. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81039. if (space == BABYLON.Space.LOCAL) {
  81040. var lm = this.getLocalMatrix();
  81041. result.x = lm.m[12];
  81042. result.y = lm.m[13];
  81043. result.z = lm.m[14];
  81044. }
  81045. else {
  81046. var wm = null;
  81047. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81048. if (mesh) {
  81049. wm = mesh.getWorldMatrix();
  81050. }
  81051. this._skeleton.computeAbsoluteTransforms();
  81052. var tmat = Bone._tmpMats[0];
  81053. if (mesh && wm) {
  81054. tmat.copyFrom(this.getAbsoluteTransform());
  81055. tmat.multiplyToRef(wm, tmat);
  81056. }
  81057. else {
  81058. tmat = this.getAbsoluteTransform();
  81059. }
  81060. result.x = tmat.m[12];
  81061. result.y = tmat.m[13];
  81062. result.z = tmat.m[14];
  81063. }
  81064. };
  81065. /**
  81066. * Get the absolute position of the bone (world space)
  81067. * @param mesh The mesh that this bone is attached to
  81068. * @returns The absolute position of the bone
  81069. */
  81070. Bone.prototype.getAbsolutePosition = function (mesh) {
  81071. if (mesh === void 0) { mesh = null; }
  81072. var pos = BABYLON.Vector3.Zero();
  81073. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81074. return pos;
  81075. };
  81076. /**
  81077. * Copy the absolute position of the bone (world space) to the result param
  81078. * @param mesh The mesh that this bone is attached to
  81079. * @param result The vector3 to copy the absolute position to
  81080. */
  81081. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  81082. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  81083. };
  81084. /**
  81085. * Compute the absolute transforms of this bone and its children
  81086. */
  81087. Bone.prototype.computeAbsoluteTransforms = function () {
  81088. this._compose();
  81089. if (this._parent) {
  81090. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81091. }
  81092. else {
  81093. this._absoluteTransform.copyFrom(this._localMatrix);
  81094. var poseMatrix = this._skeleton.getPoseMatrix();
  81095. if (poseMatrix) {
  81096. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  81097. }
  81098. }
  81099. var children = this.children;
  81100. var len = children.length;
  81101. for (var i = 0; i < len; i++) {
  81102. children[i].computeAbsoluteTransforms();
  81103. }
  81104. };
  81105. /**
  81106. * Get the world direction from an axis that is in the local space of the bone
  81107. * @param localAxis The local direction that is used to compute the world direction
  81108. * @param mesh The mesh that this bone is attached to
  81109. * @returns The world direction
  81110. */
  81111. Bone.prototype.getDirection = function (localAxis, mesh) {
  81112. if (mesh === void 0) { mesh = null; }
  81113. var result = BABYLON.Vector3.Zero();
  81114. this.getDirectionToRef(localAxis, mesh, result);
  81115. return result;
  81116. };
  81117. /**
  81118. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  81119. * @param localAxis The local direction that is used to compute the world direction
  81120. * @param mesh The mesh that this bone is attached to
  81121. * @param result The vector3 that the world direction will be copied to
  81122. */
  81123. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  81124. if (mesh === void 0) { mesh = null; }
  81125. var wm = null;
  81126. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81127. if (mesh) {
  81128. wm = mesh.getWorldMatrix();
  81129. }
  81130. this._skeleton.computeAbsoluteTransforms();
  81131. var mat = Bone._tmpMats[0];
  81132. mat.copyFrom(this.getAbsoluteTransform());
  81133. if (mesh && wm) {
  81134. mat.multiplyToRef(wm, mat);
  81135. }
  81136. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  81137. result.normalize();
  81138. };
  81139. /**
  81140. * Get the euler rotation of the bone in local or world space
  81141. * @param space The space that the rotation should be in
  81142. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81143. * @returns The euler rotation
  81144. */
  81145. Bone.prototype.getRotation = function (space, mesh) {
  81146. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81147. if (mesh === void 0) { mesh = null; }
  81148. var result = BABYLON.Vector3.Zero();
  81149. this.getRotationToRef(space, mesh, result);
  81150. return result;
  81151. };
  81152. /**
  81153. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  81154. * @param space The space that the rotation should be in
  81155. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81156. * @param result The vector3 that the rotation should be copied to
  81157. */
  81158. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  81159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81160. if (mesh === void 0) { mesh = null; }
  81161. var quat = Bone._tmpQuat;
  81162. this.getRotationQuaternionToRef(space, mesh, quat);
  81163. quat.toEulerAnglesToRef(result);
  81164. };
  81165. /**
  81166. * Get the quaternion rotation of the bone in either local or world space
  81167. * @param space The space that the rotation should be in
  81168. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81169. * @returns The quaternion rotation
  81170. */
  81171. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  81172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81173. if (mesh === void 0) { mesh = null; }
  81174. var result = BABYLON.Quaternion.Identity();
  81175. this.getRotationQuaternionToRef(space, mesh, result);
  81176. return result;
  81177. };
  81178. /**
  81179. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  81180. * @param space The space that the rotation should be in
  81181. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81182. * @param result The quaternion that the rotation should be copied to
  81183. */
  81184. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  81185. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81186. if (mesh === void 0) { mesh = null; }
  81187. if (space == BABYLON.Space.LOCAL) {
  81188. this._decompose();
  81189. result.copyFrom(this._localRotation);
  81190. }
  81191. else {
  81192. var mat = Bone._tmpMats[0];
  81193. var amat = this.getAbsoluteTransform();
  81194. if (mesh) {
  81195. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81196. }
  81197. else {
  81198. mat.copyFrom(amat);
  81199. }
  81200. mat.m[0] *= this._scalingDeterminant;
  81201. mat.m[1] *= this._scalingDeterminant;
  81202. mat.m[2] *= this._scalingDeterminant;
  81203. mat.decompose(undefined, result, undefined);
  81204. }
  81205. };
  81206. /**
  81207. * Get the rotation matrix of the bone in local or world space
  81208. * @param space The space that the rotation should be in
  81209. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81210. * @returns The rotation matrix
  81211. */
  81212. Bone.prototype.getRotationMatrix = function (space, mesh) {
  81213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81214. var result = BABYLON.Matrix.Identity();
  81215. this.getRotationMatrixToRef(space, mesh, result);
  81216. return result;
  81217. };
  81218. /**
  81219. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  81220. * @param space The space that the rotation should be in
  81221. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81222. * @param result The quaternion that the rotation should be copied to
  81223. */
  81224. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  81225. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81226. if (space == BABYLON.Space.LOCAL) {
  81227. this.getLocalMatrix().getRotationMatrixToRef(result);
  81228. }
  81229. else {
  81230. var mat = Bone._tmpMats[0];
  81231. var amat = this.getAbsoluteTransform();
  81232. if (mesh) {
  81233. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81234. }
  81235. else {
  81236. mat.copyFrom(amat);
  81237. }
  81238. mat.m[0] *= this._scalingDeterminant;
  81239. mat.m[1] *= this._scalingDeterminant;
  81240. mat.m[2] *= this._scalingDeterminant;
  81241. mat.getRotationMatrixToRef(result);
  81242. }
  81243. };
  81244. /**
  81245. * Get the world position of a point that is in the local space of the bone
  81246. * @param position The local position
  81247. * @param mesh The mesh that this bone is attached to
  81248. * @returns The world position
  81249. */
  81250. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  81251. if (mesh === void 0) { mesh = null; }
  81252. var result = BABYLON.Vector3.Zero();
  81253. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  81254. return result;
  81255. };
  81256. /**
  81257. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  81258. * @param position The local position
  81259. * @param mesh The mesh that this bone is attached to
  81260. * @param result The vector3 that the world position should be copied to
  81261. */
  81262. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  81263. if (mesh === void 0) { mesh = null; }
  81264. var wm = null;
  81265. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81266. if (mesh) {
  81267. wm = mesh.getWorldMatrix();
  81268. }
  81269. this._skeleton.computeAbsoluteTransforms();
  81270. var tmat = Bone._tmpMats[0];
  81271. if (mesh && wm) {
  81272. tmat.copyFrom(this.getAbsoluteTransform());
  81273. tmat.multiplyToRef(wm, tmat);
  81274. }
  81275. else {
  81276. tmat = this.getAbsoluteTransform();
  81277. }
  81278. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81279. };
  81280. /**
  81281. * Get the local position of a point that is in world space
  81282. * @param position The world position
  81283. * @param mesh The mesh that this bone is attached to
  81284. * @returns The local position
  81285. */
  81286. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  81287. if (mesh === void 0) { mesh = null; }
  81288. var result = BABYLON.Vector3.Zero();
  81289. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  81290. return result;
  81291. };
  81292. /**
  81293. * Get the local position of a point that is in world space and copy it to the result param
  81294. * @param position The world position
  81295. * @param mesh The mesh that this bone is attached to
  81296. * @param result The vector3 that the local position should be copied to
  81297. */
  81298. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  81299. if (mesh === void 0) { mesh = null; }
  81300. var wm = null;
  81301. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81302. if (mesh) {
  81303. wm = mesh.getWorldMatrix();
  81304. }
  81305. this._skeleton.computeAbsoluteTransforms();
  81306. var tmat = Bone._tmpMats[0];
  81307. tmat.copyFrom(this.getAbsoluteTransform());
  81308. if (mesh && wm) {
  81309. tmat.multiplyToRef(wm, tmat);
  81310. }
  81311. tmat.invert();
  81312. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81313. };
  81314. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81315. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  81316. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81317. return Bone;
  81318. }(BABYLON.Node));
  81319. BABYLON.Bone = Bone;
  81320. })(BABYLON || (BABYLON = {}));
  81321. //# sourceMappingURL=babylon.bone.js.map
  81322. var BABYLON;
  81323. (function (BABYLON) {
  81324. /**
  81325. * Class used to apply inverse kinematics to bones
  81326. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  81327. */
  81328. var BoneIKController = /** @class */ (function () {
  81329. /**
  81330. * Creates a new BoneIKController
  81331. * @param mesh defines the mesh to control
  81332. * @param bone defines the bone to control
  81333. * @param options defines options to set up the controller
  81334. */
  81335. function BoneIKController(mesh, bone, options) {
  81336. /**
  81337. * Gets or sets the target position
  81338. */
  81339. this.targetPosition = BABYLON.Vector3.Zero();
  81340. /**
  81341. * Gets or sets the pole target position
  81342. */
  81343. this.poleTargetPosition = BABYLON.Vector3.Zero();
  81344. /**
  81345. * Gets or sets the pole target local offset
  81346. */
  81347. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  81348. /**
  81349. * Gets or sets the pole angle
  81350. */
  81351. this.poleAngle = 0;
  81352. /**
  81353. * 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)
  81354. */
  81355. this.slerpAmount = 1;
  81356. this._bone1Quat = BABYLON.Quaternion.Identity();
  81357. this._bone1Mat = BABYLON.Matrix.Identity();
  81358. this._bone2Ang = Math.PI;
  81359. this._maxAngle = Math.PI;
  81360. this._rightHandedSystem = false;
  81361. this._bendAxis = BABYLON.Vector3.Right();
  81362. this._slerping = false;
  81363. this._adjustRoll = 0;
  81364. this._bone2 = bone;
  81365. this._bone1 = bone.getParent();
  81366. if (!this._bone1) {
  81367. return;
  81368. }
  81369. this.mesh = mesh;
  81370. var bonePos = bone.getPosition();
  81371. if (bone.getAbsoluteTransform().determinant() > 0) {
  81372. this._rightHandedSystem = true;
  81373. this._bendAxis.x = 0;
  81374. this._bendAxis.y = 0;
  81375. this._bendAxis.z = -1;
  81376. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  81377. this._adjustRoll = Math.PI * .5;
  81378. this._bendAxis.z = 1;
  81379. }
  81380. }
  81381. if (this._bone1.length) {
  81382. var boneScale1 = this._bone1.getScale();
  81383. var boneScale2 = this._bone2.getScale();
  81384. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  81385. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  81386. }
  81387. else if (this._bone1.children[0]) {
  81388. mesh.computeWorldMatrix(true);
  81389. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  81390. var pos2 = this._bone2.getAbsolutePosition(mesh);
  81391. var pos3 = this._bone1.getAbsolutePosition(mesh);
  81392. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  81393. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  81394. }
  81395. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  81396. this.maxAngle = Math.PI;
  81397. if (options) {
  81398. if (options.targetMesh) {
  81399. this.targetMesh = options.targetMesh;
  81400. this.targetMesh.computeWorldMatrix(true);
  81401. }
  81402. if (options.poleTargetMesh) {
  81403. this.poleTargetMesh = options.poleTargetMesh;
  81404. this.poleTargetMesh.computeWorldMatrix(true);
  81405. }
  81406. else if (options.poleTargetBone) {
  81407. this.poleTargetBone = options.poleTargetBone;
  81408. }
  81409. else if (this._bone1.getParent()) {
  81410. this.poleTargetBone = this._bone1.getParent();
  81411. }
  81412. if (options.poleTargetLocalOffset) {
  81413. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  81414. }
  81415. if (options.poleAngle) {
  81416. this.poleAngle = options.poleAngle;
  81417. }
  81418. if (options.bendAxis) {
  81419. this._bendAxis.copyFrom(options.bendAxis);
  81420. }
  81421. if (options.maxAngle) {
  81422. this.maxAngle = options.maxAngle;
  81423. }
  81424. if (options.slerpAmount) {
  81425. this.slerpAmount = options.slerpAmount;
  81426. }
  81427. }
  81428. }
  81429. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  81430. /**
  81431. * Gets or sets maximum allowed angle
  81432. */
  81433. get: function () {
  81434. return this._maxAngle;
  81435. },
  81436. set: function (value) {
  81437. this._setMaxAngle(value);
  81438. },
  81439. enumerable: true,
  81440. configurable: true
  81441. });
  81442. BoneIKController.prototype._setMaxAngle = function (ang) {
  81443. if (ang < 0) {
  81444. ang = 0;
  81445. }
  81446. if (ang > Math.PI || ang == undefined) {
  81447. ang = Math.PI;
  81448. }
  81449. this._maxAngle = ang;
  81450. var a = this._bone1Length;
  81451. var b = this._bone2Length;
  81452. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  81453. };
  81454. /**
  81455. * Force the controller to update the bones
  81456. */
  81457. BoneIKController.prototype.update = function () {
  81458. var bone1 = this._bone1;
  81459. if (!bone1) {
  81460. return;
  81461. }
  81462. var target = this.targetPosition;
  81463. var poleTarget = this.poleTargetPosition;
  81464. var mat1 = BoneIKController._tmpMats[0];
  81465. var mat2 = BoneIKController._tmpMats[1];
  81466. if (this.targetMesh) {
  81467. target.copyFrom(this.targetMesh.getAbsolutePosition());
  81468. }
  81469. if (this.poleTargetBone) {
  81470. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  81471. }
  81472. else if (this.poleTargetMesh) {
  81473. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  81474. }
  81475. var bonePos = BoneIKController._tmpVecs[0];
  81476. var zaxis = BoneIKController._tmpVecs[1];
  81477. var xaxis = BoneIKController._tmpVecs[2];
  81478. var yaxis = BoneIKController._tmpVecs[3];
  81479. var upAxis = BoneIKController._tmpVecs[4];
  81480. var _tmpQuat = BoneIKController._tmpQuat;
  81481. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  81482. poleTarget.subtractToRef(bonePos, upAxis);
  81483. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  81484. upAxis.y = 1;
  81485. }
  81486. else {
  81487. upAxis.normalize();
  81488. }
  81489. target.subtractToRef(bonePos, yaxis);
  81490. yaxis.normalize();
  81491. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  81492. zaxis.normalize();
  81493. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  81494. xaxis.normalize();
  81495. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  81496. var a = this._bone1Length;
  81497. var b = this._bone2Length;
  81498. var c = BABYLON.Vector3.Distance(bonePos, target);
  81499. if (this._maxReach > 0) {
  81500. c = Math.min(this._maxReach, c);
  81501. }
  81502. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  81503. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  81504. if (acosa > 1) {
  81505. acosa = 1;
  81506. }
  81507. if (acosb > 1) {
  81508. acosb = 1;
  81509. }
  81510. if (acosa < -1) {
  81511. acosa = -1;
  81512. }
  81513. if (acosb < -1) {
  81514. acosb = -1;
  81515. }
  81516. var angA = Math.acos(acosa);
  81517. var angB = Math.acos(acosb);
  81518. var angC = -angA - angB;
  81519. if (this._rightHandedSystem) {
  81520. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  81521. mat2.multiplyToRef(mat1, mat1);
  81522. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  81523. mat2.multiplyToRef(mat1, mat1);
  81524. }
  81525. else {
  81526. var _tmpVec = BoneIKController._tmpVecs[5];
  81527. _tmpVec.copyFrom(this._bendAxis);
  81528. _tmpVec.x *= -1;
  81529. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  81530. mat2.multiplyToRef(mat1, mat1);
  81531. }
  81532. if (this.poleAngle) {
  81533. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  81534. mat1.multiplyToRef(mat2, mat1);
  81535. }
  81536. if (this._bone1) {
  81537. if (this.slerpAmount < 1) {
  81538. if (!this._slerping) {
  81539. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  81540. }
  81541. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  81542. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  81543. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  81544. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  81545. this._slerping = true;
  81546. }
  81547. else {
  81548. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  81549. this._bone1Mat.copyFrom(mat1);
  81550. this._slerping = false;
  81551. }
  81552. }
  81553. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  81554. this._bone2Ang = angC;
  81555. };
  81556. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81557. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  81558. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81559. return BoneIKController;
  81560. }());
  81561. BABYLON.BoneIKController = BoneIKController;
  81562. })(BABYLON || (BABYLON = {}));
  81563. //# sourceMappingURL=babylon.boneIKController.js.map
  81564. var BABYLON;
  81565. (function (BABYLON) {
  81566. /**
  81567. * Class used to make a bone look toward a point in space
  81568. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  81569. */
  81570. var BoneLookController = /** @class */ (function () {
  81571. /**
  81572. * Create a BoneLookController
  81573. * @param mesh the mesh that the bone belongs to
  81574. * @param bone the bone that will be looking to the target
  81575. * @param target the target Vector3 to look at
  81576. * @param settings optional settings:
  81577. * * maxYaw: the maximum angle the bone will yaw to
  81578. * * minYaw: the minimum angle the bone will yaw to
  81579. * * maxPitch: the maximum angle the bone will pitch to
  81580. * * minPitch: the minimum angle the bone will yaw to
  81581. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  81582. * * upAxis: the up axis of the coordinate system
  81583. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  81584. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  81585. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  81586. * * adjustYaw: used to make an adjustment to the yaw of the bone
  81587. * * adjustPitch: used to make an adjustment to the pitch of the bone
  81588. * * adjustRoll: used to make an adjustment to the roll of the bone
  81589. **/
  81590. function BoneLookController(mesh, bone, target, options) {
  81591. /**
  81592. * The up axis of the coordinate system that is used when the bone is rotated
  81593. */
  81594. this.upAxis = BABYLON.Vector3.Up();
  81595. /**
  81596. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  81597. */
  81598. this.upAxisSpace = BABYLON.Space.LOCAL;
  81599. /**
  81600. * Used to make an adjustment to the yaw of the bone
  81601. */
  81602. this.adjustYaw = 0;
  81603. /**
  81604. * Used to make an adjustment to the pitch of the bone
  81605. */
  81606. this.adjustPitch = 0;
  81607. /**
  81608. * Used to make an adjustment to the roll of the bone
  81609. */
  81610. this.adjustRoll = 0;
  81611. /**
  81612. * 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)
  81613. */
  81614. this.slerpAmount = 1;
  81615. this._boneQuat = BABYLON.Quaternion.Identity();
  81616. this._slerping = false;
  81617. this._firstFrameSkipped = false;
  81618. this._fowardAxis = BABYLON.Vector3.Forward();
  81619. this.mesh = mesh;
  81620. this.bone = bone;
  81621. this.target = target;
  81622. if (options) {
  81623. if (options.adjustYaw) {
  81624. this.adjustYaw = options.adjustYaw;
  81625. }
  81626. if (options.adjustPitch) {
  81627. this.adjustPitch = options.adjustPitch;
  81628. }
  81629. if (options.adjustRoll) {
  81630. this.adjustRoll = options.adjustRoll;
  81631. }
  81632. if (options.maxYaw != null) {
  81633. this.maxYaw = options.maxYaw;
  81634. }
  81635. else {
  81636. this.maxYaw = Math.PI;
  81637. }
  81638. if (options.minYaw != null) {
  81639. this.minYaw = options.minYaw;
  81640. }
  81641. else {
  81642. this.minYaw = -Math.PI;
  81643. }
  81644. if (options.maxPitch != null) {
  81645. this.maxPitch = options.maxPitch;
  81646. }
  81647. else {
  81648. this.maxPitch = Math.PI;
  81649. }
  81650. if (options.minPitch != null) {
  81651. this.minPitch = options.minPitch;
  81652. }
  81653. else {
  81654. this.minPitch = -Math.PI;
  81655. }
  81656. if (options.slerpAmount != null) {
  81657. this.slerpAmount = options.slerpAmount;
  81658. }
  81659. if (options.upAxis != null) {
  81660. this.upAxis = options.upAxis;
  81661. }
  81662. if (options.upAxisSpace != null) {
  81663. this.upAxisSpace = options.upAxisSpace;
  81664. }
  81665. if (options.yawAxis != null || options.pitchAxis != null) {
  81666. var newYawAxis = BABYLON.Axis.Y;
  81667. var newPitchAxis = BABYLON.Axis.X;
  81668. if (options.yawAxis != null) {
  81669. newYawAxis = options.yawAxis.clone();
  81670. newYawAxis.normalize();
  81671. }
  81672. if (options.pitchAxis != null) {
  81673. newPitchAxis = options.pitchAxis.clone();
  81674. newPitchAxis.normalize();
  81675. }
  81676. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  81677. this._transformYawPitch = BABYLON.Matrix.Identity();
  81678. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  81679. this._transformYawPitchInv = this._transformYawPitch.clone();
  81680. this._transformYawPitch.invert();
  81681. }
  81682. }
  81683. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  81684. this.upAxisSpace = BABYLON.Space.LOCAL;
  81685. }
  81686. }
  81687. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  81688. /**
  81689. * Gets or sets the minimum yaw angle that the bone can look to
  81690. */
  81691. get: function () {
  81692. return this._minYaw;
  81693. },
  81694. set: function (value) {
  81695. this._minYaw = value;
  81696. this._minYawSin = Math.sin(value);
  81697. this._minYawCos = Math.cos(value);
  81698. if (this._maxYaw != null) {
  81699. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81700. this._yawRange = this._maxYaw - this._minYaw;
  81701. }
  81702. },
  81703. enumerable: true,
  81704. configurable: true
  81705. });
  81706. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  81707. /**
  81708. * Gets or sets the maximum yaw angle that the bone can look to
  81709. */
  81710. get: function () {
  81711. return this._maxYaw;
  81712. },
  81713. set: function (value) {
  81714. this._maxYaw = value;
  81715. this._maxYawSin = Math.sin(value);
  81716. this._maxYawCos = Math.cos(value);
  81717. if (this._minYaw != null) {
  81718. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81719. this._yawRange = this._maxYaw - this._minYaw;
  81720. }
  81721. },
  81722. enumerable: true,
  81723. configurable: true
  81724. });
  81725. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  81726. /**
  81727. * Gets or sets the minimum pitch angle that the bone can look to
  81728. */
  81729. get: function () {
  81730. return this._minPitch;
  81731. },
  81732. set: function (value) {
  81733. this._minPitch = value;
  81734. this._minPitchTan = Math.tan(value);
  81735. },
  81736. enumerable: true,
  81737. configurable: true
  81738. });
  81739. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  81740. /**
  81741. * Gets or sets the maximum pitch angle that the bone can look to
  81742. */
  81743. get: function () {
  81744. return this._maxPitch;
  81745. },
  81746. set: function (value) {
  81747. this._maxPitch = value;
  81748. this._maxPitchTan = Math.tan(value);
  81749. },
  81750. enumerable: true,
  81751. configurable: true
  81752. });
  81753. /**
  81754. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  81755. */
  81756. BoneLookController.prototype.update = function () {
  81757. //skip the first frame when slerping so that the mesh rotation is correct
  81758. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  81759. this._firstFrameSkipped = true;
  81760. return;
  81761. }
  81762. var bone = this.bone;
  81763. var bonePos = BoneLookController._tmpVecs[0];
  81764. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  81765. var target = this.target;
  81766. var _tmpMat1 = BoneLookController._tmpMats[0];
  81767. var _tmpMat2 = BoneLookController._tmpMats[1];
  81768. var mesh = this.mesh;
  81769. var parentBone = bone.getParent();
  81770. var upAxis = BoneLookController._tmpVecs[1];
  81771. upAxis.copyFrom(this.upAxis);
  81772. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  81773. if (this._transformYawPitch) {
  81774. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  81775. }
  81776. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  81777. }
  81778. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81779. mesh.getDirectionToRef(upAxis, upAxis);
  81780. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81781. upAxis.normalize();
  81782. }
  81783. }
  81784. var checkYaw = false;
  81785. var checkPitch = false;
  81786. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81787. checkYaw = true;
  81788. }
  81789. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81790. checkPitch = true;
  81791. }
  81792. if (checkYaw || checkPitch) {
  81793. var spaceMat = BoneLookController._tmpMats[2];
  81794. var spaceMatInv = BoneLookController._tmpMats[3];
  81795. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81796. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81797. }
  81798. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81799. spaceMat.copyFrom(mesh.getWorldMatrix());
  81800. }
  81801. else {
  81802. var forwardAxis = BoneLookController._tmpVecs[2];
  81803. forwardAxis.copyFrom(this._fowardAxis);
  81804. if (this._transformYawPitch) {
  81805. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81806. }
  81807. if (parentBone) {
  81808. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81809. }
  81810. else {
  81811. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81812. }
  81813. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81814. rightAxis.normalize();
  81815. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81816. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81817. }
  81818. spaceMat.invertToRef(spaceMatInv);
  81819. var xzlen = null;
  81820. if (checkPitch) {
  81821. var localTarget = BoneLookController._tmpVecs[3];
  81822. target.subtractToRef(bonePos, localTarget);
  81823. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81824. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81825. var pitch = Math.atan2(localTarget.y, xzlen);
  81826. var newPitch = pitch;
  81827. if (pitch > this._maxPitch) {
  81828. localTarget.y = this._maxPitchTan * xzlen;
  81829. newPitch = this._maxPitch;
  81830. }
  81831. else if (pitch < this._minPitch) {
  81832. localTarget.y = this._minPitchTan * xzlen;
  81833. newPitch = this._minPitch;
  81834. }
  81835. if (pitch != newPitch) {
  81836. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81837. localTarget.addInPlace(bonePos);
  81838. target = localTarget;
  81839. }
  81840. }
  81841. if (checkYaw) {
  81842. var localTarget = BoneLookController._tmpVecs[4];
  81843. target.subtractToRef(bonePos, localTarget);
  81844. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81845. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81846. var newYaw = yaw;
  81847. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81848. if (xzlen == null) {
  81849. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81850. }
  81851. if (this._yawRange > Math.PI) {
  81852. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81853. localTarget.z = this._maxYawCos * xzlen;
  81854. localTarget.x = this._maxYawSin * xzlen;
  81855. newYaw = this._maxYaw;
  81856. }
  81857. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81858. localTarget.z = this._minYawCos * xzlen;
  81859. localTarget.x = this._minYawSin * xzlen;
  81860. newYaw = this._minYaw;
  81861. }
  81862. }
  81863. else {
  81864. if (yaw > this._maxYaw) {
  81865. localTarget.z = this._maxYawCos * xzlen;
  81866. localTarget.x = this._maxYawSin * xzlen;
  81867. newYaw = this._maxYaw;
  81868. }
  81869. else if (yaw < this._minYaw) {
  81870. localTarget.z = this._minYawCos * xzlen;
  81871. localTarget.x = this._minYawSin * xzlen;
  81872. newYaw = this._minYaw;
  81873. }
  81874. }
  81875. }
  81876. if (this._slerping && this._yawRange > Math.PI) {
  81877. //are we going to be crossing into the min/max region?
  81878. var boneFwd = BoneLookController._tmpVecs[8];
  81879. boneFwd.copyFrom(BABYLON.Axis.Z);
  81880. if (this._transformYawPitch) {
  81881. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81882. }
  81883. var boneRotMat = BoneLookController._tmpMats[4];
  81884. this._boneQuat.toRotationMatrix(boneRotMat);
  81885. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81886. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81887. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81888. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81889. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81890. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81891. if (angBtwTar > angBtwMidYaw) {
  81892. if (xzlen == null) {
  81893. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81894. }
  81895. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81896. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81897. if (angBtwMin < angBtwMax) {
  81898. newYaw = boneYaw + Math.PI * .75;
  81899. localTarget.z = Math.cos(newYaw) * xzlen;
  81900. localTarget.x = Math.sin(newYaw) * xzlen;
  81901. }
  81902. else {
  81903. newYaw = boneYaw - Math.PI * .75;
  81904. localTarget.z = Math.cos(newYaw) * xzlen;
  81905. localTarget.x = Math.sin(newYaw) * xzlen;
  81906. }
  81907. }
  81908. }
  81909. if (yaw != newYaw) {
  81910. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81911. localTarget.addInPlace(bonePos);
  81912. target = localTarget;
  81913. }
  81914. }
  81915. }
  81916. var zaxis = BoneLookController._tmpVecs[5];
  81917. var xaxis = BoneLookController._tmpVecs[6];
  81918. var yaxis = BoneLookController._tmpVecs[7];
  81919. var _tmpQuat = BoneLookController._tmpQuat;
  81920. target.subtractToRef(bonePos, zaxis);
  81921. zaxis.normalize();
  81922. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81923. xaxis.normalize();
  81924. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81925. yaxis.normalize();
  81926. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81927. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81928. return;
  81929. }
  81930. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81931. return;
  81932. }
  81933. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81934. return;
  81935. }
  81936. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81937. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81938. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81939. }
  81940. if (this.slerpAmount < 1) {
  81941. if (!this._slerping) {
  81942. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81943. }
  81944. if (this._transformYawPitch) {
  81945. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81946. }
  81947. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81948. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81949. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81950. this._slerping = true;
  81951. }
  81952. else {
  81953. if (this._transformYawPitch) {
  81954. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81955. }
  81956. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81957. this._slerping = false;
  81958. }
  81959. };
  81960. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81961. var angDiff = ang2 - ang1;
  81962. angDiff %= Math.PI * 2;
  81963. if (angDiff > Math.PI) {
  81964. angDiff -= Math.PI * 2;
  81965. }
  81966. else if (angDiff < -Math.PI) {
  81967. angDiff += Math.PI * 2;
  81968. }
  81969. return angDiff;
  81970. };
  81971. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81972. ang1 %= (2 * Math.PI);
  81973. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81974. ang2 %= (2 * Math.PI);
  81975. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81976. var ab = 0;
  81977. if (ang1 < ang2) {
  81978. ab = ang2 - ang1;
  81979. }
  81980. else {
  81981. ab = ang1 - ang2;
  81982. }
  81983. if (ab > Math.PI) {
  81984. ab = Math.PI * 2 - ab;
  81985. }
  81986. return ab;
  81987. };
  81988. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81989. ang %= (2 * Math.PI);
  81990. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81991. ang1 %= (2 * Math.PI);
  81992. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81993. ang2 %= (2 * Math.PI);
  81994. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81995. if (ang1 < ang2) {
  81996. if (ang > ang1 && ang < ang2) {
  81997. return true;
  81998. }
  81999. }
  82000. else {
  82001. if (ang > ang2 && ang < ang1) {
  82002. return true;
  82003. }
  82004. }
  82005. return false;
  82006. };
  82007. 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()];
  82008. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82009. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82010. return BoneLookController;
  82011. }());
  82012. BABYLON.BoneLookController = BoneLookController;
  82013. })(BABYLON || (BABYLON = {}));
  82014. //# sourceMappingURL=babylon.boneLookController.js.map
  82015. var BABYLON;
  82016. (function (BABYLON) {
  82017. /**
  82018. * Class used to handle skinning animations
  82019. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82020. */
  82021. var Skeleton = /** @class */ (function () {
  82022. /**
  82023. * Creates a new skeleton
  82024. * @param name defines the skeleton name
  82025. * @param id defines the skeleton Id
  82026. * @param scene defines the hosting scene
  82027. */
  82028. function Skeleton(
  82029. /** defines the skeleton name */
  82030. name,
  82031. /** defines the skeleton Id */
  82032. id, scene) {
  82033. this.name = name;
  82034. this.id = id;
  82035. /**
  82036. * Gets the list of child bones
  82037. */
  82038. this.bones = new Array();
  82039. /**
  82040. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82041. */
  82042. this.needInitialSkinMatrix = false;
  82043. this._isDirty = true;
  82044. this._meshesWithPoseMatrix = new Array();
  82045. this._identity = BABYLON.Matrix.Identity();
  82046. this._ranges = {};
  82047. this._lastAbsoluteTransformsUpdateId = -1;
  82048. /**
  82049. * Specifies if the skeleton should be serialized
  82050. */
  82051. this.doNotSerialize = false;
  82052. this._animationPropertiesOverride = null;
  82053. // Events
  82054. /**
  82055. * An observable triggered before computing the skeleton's matrices
  82056. */
  82057. this.onBeforeComputeObservable = new BABYLON.Observable();
  82058. this.bones = [];
  82059. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82060. scene.skeletons.push(this);
  82061. //make sure it will recalculate the matrix next time prepare is called.
  82062. this._isDirty = true;
  82063. }
  82064. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82065. /**
  82066. * Gets or sets the animation properties override
  82067. */
  82068. get: function () {
  82069. if (!this._animationPropertiesOverride) {
  82070. return this._scene.animationPropertiesOverride;
  82071. }
  82072. return this._animationPropertiesOverride;
  82073. },
  82074. set: function (value) {
  82075. this._animationPropertiesOverride = value;
  82076. },
  82077. enumerable: true,
  82078. configurable: true
  82079. });
  82080. // Members
  82081. /**
  82082. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  82083. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  82084. * @returns a Float32Array containing matrices data
  82085. */
  82086. Skeleton.prototype.getTransformMatrices = function (mesh) {
  82087. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  82088. return mesh._bonesTransformMatrices;
  82089. }
  82090. if (!this._transformMatrices) {
  82091. this.prepare();
  82092. }
  82093. return this._transformMatrices;
  82094. };
  82095. /**
  82096. * Gets the current hosting scene
  82097. * @returns a scene object
  82098. */
  82099. Skeleton.prototype.getScene = function () {
  82100. return this._scene;
  82101. };
  82102. // Methods
  82103. /**
  82104. * Gets a string representing the current skeleton data
  82105. * @param fullDetails defines a boolean indicating if we want a verbose version
  82106. * @returns a string representing the current skeleton data
  82107. */
  82108. Skeleton.prototype.toString = function (fullDetails) {
  82109. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  82110. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  82111. if (fullDetails) {
  82112. ret += ", Ranges: {";
  82113. var first = true;
  82114. for (var name_1 in this._ranges) {
  82115. if (first) {
  82116. ret += ", ";
  82117. first = false;
  82118. }
  82119. ret += name_1;
  82120. }
  82121. ret += "}";
  82122. }
  82123. return ret;
  82124. };
  82125. /**
  82126. * Get bone's index searching by name
  82127. * @param name defines bone's name to search for
  82128. * @return the indice of the bone. Returns -1 if not found
  82129. */
  82130. Skeleton.prototype.getBoneIndexByName = function (name) {
  82131. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  82132. if (this.bones[boneIndex].name === name) {
  82133. return boneIndex;
  82134. }
  82135. }
  82136. return -1;
  82137. };
  82138. /**
  82139. * Creater a new animation range
  82140. * @param name defines the name of the range
  82141. * @param from defines the start key
  82142. * @param to defines the end key
  82143. */
  82144. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  82145. // check name not already in use
  82146. if (!this._ranges[name]) {
  82147. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  82148. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82149. if (this.bones[i].animations[0]) {
  82150. this.bones[i].animations[0].createRange(name, from, to);
  82151. }
  82152. }
  82153. }
  82154. };
  82155. /**
  82156. * Delete a specific animation range
  82157. * @param name defines the name of the range
  82158. * @param deleteFrames defines if frames must be removed as well
  82159. */
  82160. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  82161. if (deleteFrames === void 0) { deleteFrames = true; }
  82162. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82163. if (this.bones[i].animations[0]) {
  82164. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  82165. }
  82166. }
  82167. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  82168. };
  82169. /**
  82170. * Gets a specific animation range
  82171. * @param name defines the name of the range to look for
  82172. * @returns the requested animation range or null if not found
  82173. */
  82174. Skeleton.prototype.getAnimationRange = function (name) {
  82175. return this._ranges[name];
  82176. };
  82177. /**
  82178. * Gets the list of all animation ranges defined on this skeleton
  82179. * @returns an array
  82180. */
  82181. Skeleton.prototype.getAnimationRanges = function () {
  82182. var animationRanges = [];
  82183. var name;
  82184. var i = 0;
  82185. for (name in this._ranges) {
  82186. animationRanges[i] = this._ranges[name];
  82187. i++;
  82188. }
  82189. return animationRanges;
  82190. };
  82191. /**
  82192. * Copy animation range from a source skeleton.
  82193. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  82194. * @param source defines the source skeleton
  82195. * @param name defines the name of the range to copy
  82196. * @param rescaleAsRequired defines if rescaling must be applied if required
  82197. * @returns true if operation was successful
  82198. */
  82199. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  82200. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82201. if (this._ranges[name] || !source.getAnimationRange(name)) {
  82202. return false;
  82203. }
  82204. var ret = true;
  82205. var frameOffset = this._getHighestAnimationFrame() + 1;
  82206. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  82207. var boneDict = {};
  82208. var sourceBones = source.bones;
  82209. var nBones;
  82210. var i;
  82211. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  82212. boneDict[sourceBones[i].name] = sourceBones[i];
  82213. }
  82214. if (this.bones.length !== sourceBones.length) {
  82215. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  82216. ret = false;
  82217. }
  82218. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  82219. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  82220. var boneName = this.bones[i].name;
  82221. var sourceBone = boneDict[boneName];
  82222. if (sourceBone) {
  82223. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  82224. }
  82225. else {
  82226. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  82227. ret = false;
  82228. }
  82229. }
  82230. // do not call createAnimationRange(), since it also is done to bones, which was already done
  82231. var range = source.getAnimationRange(name);
  82232. if (range) {
  82233. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  82234. }
  82235. return ret;
  82236. };
  82237. /**
  82238. * Forces the skeleton to go to rest pose
  82239. */
  82240. Skeleton.prototype.returnToRest = function () {
  82241. for (var index = 0; index < this.bones.length; index++) {
  82242. this.bones[index].returnToRest();
  82243. }
  82244. };
  82245. Skeleton.prototype._getHighestAnimationFrame = function () {
  82246. var ret = 0;
  82247. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82248. if (this.bones[i].animations[0]) {
  82249. var highest = this.bones[i].animations[0].getHighestFrame();
  82250. if (ret < highest) {
  82251. ret = highest;
  82252. }
  82253. }
  82254. }
  82255. return ret;
  82256. };
  82257. /**
  82258. * Begin a specific animation range
  82259. * @param name defines the name of the range to start
  82260. * @param loop defines if looping must be turned on (false by default)
  82261. * @param speedRatio defines the speed ratio to apply (1 by default)
  82262. * @param onAnimationEnd defines a callback which will be called when animation will end
  82263. * @returns a new animatable
  82264. */
  82265. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  82266. var range = this.getAnimationRange(name);
  82267. if (!range) {
  82268. return null;
  82269. }
  82270. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  82271. };
  82272. /** @hidden */
  82273. Skeleton.prototype._markAsDirty = function () {
  82274. this._isDirty = true;
  82275. };
  82276. /** @hidden */
  82277. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  82278. this._meshesWithPoseMatrix.push(mesh);
  82279. };
  82280. /** @hidden */
  82281. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  82282. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  82283. if (index > -1) {
  82284. this._meshesWithPoseMatrix.splice(index, 1);
  82285. }
  82286. };
  82287. /** @hidden */
  82288. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  82289. this.onBeforeComputeObservable.notifyObservers(this);
  82290. for (var index = 0; index < this.bones.length; index++) {
  82291. var bone = this.bones[index];
  82292. var parentBone = bone.getParent();
  82293. if (parentBone) {
  82294. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  82295. }
  82296. else {
  82297. if (initialSkinMatrix) {
  82298. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  82299. }
  82300. else {
  82301. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  82302. }
  82303. }
  82304. if (bone._index !== -1) {
  82305. var mappedIndex = bone._index === null ? index : bone._index;
  82306. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  82307. }
  82308. }
  82309. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  82310. };
  82311. /**
  82312. * Build all resources required to render a skeleton
  82313. */
  82314. Skeleton.prototype.prepare = function () {
  82315. if (!this._isDirty) {
  82316. return;
  82317. }
  82318. if (this.needInitialSkinMatrix) {
  82319. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  82320. var mesh = this._meshesWithPoseMatrix[index];
  82321. var poseMatrix = mesh.getPoseMatrix();
  82322. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  82323. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82324. }
  82325. if (this._synchronizedWithMesh !== mesh) {
  82326. this._synchronizedWithMesh = mesh;
  82327. // Prepare bones
  82328. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  82329. var bone = this.bones[boneIndex];
  82330. if (!bone.getParent()) {
  82331. var matrix = bone.getBaseMatrix();
  82332. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  82333. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  82334. }
  82335. }
  82336. }
  82337. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  82338. }
  82339. }
  82340. else {
  82341. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  82342. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82343. }
  82344. this._computeTransformMatrices(this._transformMatrices, null);
  82345. }
  82346. this._isDirty = false;
  82347. this._scene._activeBones.addCount(this.bones.length, false);
  82348. };
  82349. /**
  82350. * Gets the list of animatables currently running for this skeleton
  82351. * @returns an array of animatables
  82352. */
  82353. Skeleton.prototype.getAnimatables = function () {
  82354. if (!this._animatables || this._animatables.length !== this.bones.length) {
  82355. this._animatables = [];
  82356. for (var index = 0; index < this.bones.length; index++) {
  82357. this._animatables.push(this.bones[index]);
  82358. }
  82359. }
  82360. return this._animatables;
  82361. };
  82362. /**
  82363. * Clone the current skeleton
  82364. * @param name defines the name of the new skeleton
  82365. * @param id defines the id of the enw skeleton
  82366. * @returns the new skeleton
  82367. */
  82368. Skeleton.prototype.clone = function (name, id) {
  82369. var result = new Skeleton(name, id || name, this._scene);
  82370. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82371. for (var index = 0; index < this.bones.length; index++) {
  82372. var source = this.bones[index];
  82373. var parentBone = null;
  82374. var parent_1 = source.getParent();
  82375. if (parent_1) {
  82376. var parentIndex = this.bones.indexOf(parent_1);
  82377. parentBone = result.bones[parentIndex];
  82378. }
  82379. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  82380. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  82381. }
  82382. if (this._ranges) {
  82383. result._ranges = {};
  82384. for (var rangeName in this._ranges) {
  82385. var range = this._ranges[rangeName];
  82386. if (range) {
  82387. result._ranges[rangeName] = range.clone();
  82388. }
  82389. }
  82390. }
  82391. this._isDirty = true;
  82392. return result;
  82393. };
  82394. /**
  82395. * Enable animation blending for this skeleton
  82396. * @param blendingSpeed defines the blending speed to apply
  82397. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  82398. */
  82399. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  82400. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  82401. this.bones.forEach(function (bone) {
  82402. bone.animations.forEach(function (animation) {
  82403. animation.enableBlending = true;
  82404. animation.blendingSpeed = blendingSpeed;
  82405. });
  82406. });
  82407. };
  82408. /**
  82409. * Releases all resources associated with the current skeleton
  82410. */
  82411. Skeleton.prototype.dispose = function () {
  82412. this._meshesWithPoseMatrix = [];
  82413. // Animations
  82414. this.getScene().stopAnimation(this);
  82415. // Remove from scene
  82416. this.getScene().removeSkeleton(this);
  82417. };
  82418. /**
  82419. * Serialize the skeleton in a JSON object
  82420. * @returns a JSON object
  82421. */
  82422. Skeleton.prototype.serialize = function () {
  82423. var serializationObject = {};
  82424. serializationObject.name = this.name;
  82425. serializationObject.id = this.id;
  82426. if (this.dimensionsAtRest) {
  82427. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  82428. }
  82429. serializationObject.bones = [];
  82430. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82431. for (var index = 0; index < this.bones.length; index++) {
  82432. var bone = this.bones[index];
  82433. var parent_2 = bone.getParent();
  82434. var serializedBone = {
  82435. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  82436. name: bone.name,
  82437. matrix: bone.getBaseMatrix().toArray(),
  82438. rest: bone.getRestPose().toArray()
  82439. };
  82440. serializationObject.bones.push(serializedBone);
  82441. if (bone.length) {
  82442. serializedBone.length = bone.length;
  82443. }
  82444. if (bone.metadata) {
  82445. serializedBone.metadata = bone.metadata;
  82446. }
  82447. if (bone.animations && bone.animations.length > 0) {
  82448. serializedBone.animation = bone.animations[0].serialize();
  82449. }
  82450. serializationObject.ranges = [];
  82451. for (var name in this._ranges) {
  82452. var source = this._ranges[name];
  82453. if (!source) {
  82454. continue;
  82455. }
  82456. var range = {};
  82457. range.name = name;
  82458. range.from = source.from;
  82459. range.to = source.to;
  82460. serializationObject.ranges.push(range);
  82461. }
  82462. }
  82463. return serializationObject;
  82464. };
  82465. /**
  82466. * Creates a new skeleton from serialized data
  82467. * @param parsedSkeleton defines the serialized data
  82468. * @param scene defines the hosting scene
  82469. * @returns a new skeleton
  82470. */
  82471. Skeleton.Parse = function (parsedSkeleton, scene) {
  82472. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  82473. if (parsedSkeleton.dimensionsAtRest) {
  82474. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  82475. }
  82476. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  82477. var index;
  82478. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  82479. var parsedBone = parsedSkeleton.bones[index];
  82480. var parentBone = null;
  82481. if (parsedBone.parentBoneIndex > -1) {
  82482. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  82483. }
  82484. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  82485. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  82486. if (parsedBone.length) {
  82487. bone.length = parsedBone.length;
  82488. }
  82489. if (parsedBone.metadata) {
  82490. bone.metadata = parsedBone.metadata;
  82491. }
  82492. if (parsedBone.animation) {
  82493. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  82494. }
  82495. }
  82496. // placed after bones, so createAnimationRange can cascade down
  82497. if (parsedSkeleton.ranges) {
  82498. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  82499. var data = parsedSkeleton.ranges[index];
  82500. skeleton.createAnimationRange(data.name, data.from, data.to);
  82501. }
  82502. }
  82503. return skeleton;
  82504. };
  82505. /**
  82506. * Compute all node absolute transforms
  82507. * @param forceUpdate defines if computation must be done even if cache is up to date
  82508. */
  82509. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  82510. if (forceUpdate === void 0) { forceUpdate = false; }
  82511. var renderId = this._scene.getRenderId();
  82512. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  82513. this.bones[0].computeAbsoluteTransforms();
  82514. this._lastAbsoluteTransformsUpdateId = renderId;
  82515. }
  82516. };
  82517. /**
  82518. * Gets the root pose matrix
  82519. * @returns a matrix
  82520. */
  82521. Skeleton.prototype.getPoseMatrix = function () {
  82522. var poseMatrix = null;
  82523. if (this._meshesWithPoseMatrix.length > 0) {
  82524. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  82525. }
  82526. return poseMatrix;
  82527. };
  82528. /**
  82529. * Sorts bones per internal index
  82530. */
  82531. Skeleton.prototype.sortBones = function () {
  82532. var bones = new Array();
  82533. var visited = new Array(this.bones.length);
  82534. for (var index = 0; index < this.bones.length; index++) {
  82535. this._sortBones(index, bones, visited);
  82536. }
  82537. this.bones = bones;
  82538. };
  82539. Skeleton.prototype._sortBones = function (index, bones, visited) {
  82540. if (visited[index]) {
  82541. return;
  82542. }
  82543. visited[index] = true;
  82544. var bone = this.bones[index];
  82545. if (bone._index === undefined) {
  82546. bone._index = index;
  82547. }
  82548. var parentBone = bone.getParent();
  82549. if (parentBone) {
  82550. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  82551. }
  82552. bones.push(bone);
  82553. };
  82554. return Skeleton;
  82555. }());
  82556. BABYLON.Skeleton = Skeleton;
  82557. })(BABYLON || (BABYLON = {}));
  82558. //# sourceMappingURL=babylon.skeleton.js.map
  82559. var BABYLON;
  82560. (function (BABYLON) {
  82561. /**
  82562. * Class representing spherical polynomial coefficients to the 3rd degree
  82563. */
  82564. var SphericalPolynomial = /** @class */ (function () {
  82565. function SphericalPolynomial() {
  82566. /**
  82567. * The x coefficients of the spherical polynomial
  82568. */
  82569. this.x = BABYLON.Vector3.Zero();
  82570. /**
  82571. * The y coefficients of the spherical polynomial
  82572. */
  82573. this.y = BABYLON.Vector3.Zero();
  82574. /**
  82575. * The z coefficients of the spherical polynomial
  82576. */
  82577. this.z = BABYLON.Vector3.Zero();
  82578. /**
  82579. * The xx coefficients of the spherical polynomial
  82580. */
  82581. this.xx = BABYLON.Vector3.Zero();
  82582. /**
  82583. * The yy coefficients of the spherical polynomial
  82584. */
  82585. this.yy = BABYLON.Vector3.Zero();
  82586. /**
  82587. * The zz coefficients of the spherical polynomial
  82588. */
  82589. this.zz = BABYLON.Vector3.Zero();
  82590. /**
  82591. * The xy coefficients of the spherical polynomial
  82592. */
  82593. this.xy = BABYLON.Vector3.Zero();
  82594. /**
  82595. * The yz coefficients of the spherical polynomial
  82596. */
  82597. this.yz = BABYLON.Vector3.Zero();
  82598. /**
  82599. * The zx coefficients of the spherical polynomial
  82600. */
  82601. this.zx = BABYLON.Vector3.Zero();
  82602. }
  82603. /**
  82604. * Adds an ambient color to the spherical polynomial
  82605. * @param color the color to add
  82606. */
  82607. SphericalPolynomial.prototype.addAmbient = function (color) {
  82608. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82609. this.xx = this.xx.add(colorVector);
  82610. this.yy = this.yy.add(colorVector);
  82611. this.zz = this.zz.add(colorVector);
  82612. };
  82613. /**
  82614. * Scales the spherical polynomial by the given amount
  82615. * @param scale the amount to scale
  82616. */
  82617. SphericalPolynomial.prototype.scale = function (scale) {
  82618. this.x = this.x.scale(scale);
  82619. this.y = this.y.scale(scale);
  82620. this.z = this.z.scale(scale);
  82621. this.xx = this.xx.scale(scale);
  82622. this.yy = this.yy.scale(scale);
  82623. this.zz = this.zz.scale(scale);
  82624. this.yz = this.yz.scale(scale);
  82625. this.zx = this.zx.scale(scale);
  82626. this.xy = this.xy.scale(scale);
  82627. };
  82628. /**
  82629. * Gets the spherical polynomial from harmonics
  82630. * @param harmonics the spherical harmonics
  82631. * @returns the spherical polynomial
  82632. */
  82633. SphericalPolynomial.FromHarmonics = function (harmonics) {
  82634. var result = new SphericalPolynomial();
  82635. result.x = harmonics.l11.scale(1.02333);
  82636. result.y = harmonics.l1_1.scale(1.02333);
  82637. result.z = harmonics.l10.scale(1.02333);
  82638. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  82639. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  82640. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  82641. result.yz = harmonics.l2_1.scale(0.858086);
  82642. result.zx = harmonics.l21.scale(0.858086);
  82643. result.xy = harmonics.l2_2.scale(0.858086);
  82644. result.scale(1.0 / Math.PI);
  82645. return result;
  82646. };
  82647. /**
  82648. * Constructs a spherical polynomial from an array.
  82649. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  82650. * @returns the spherical polynomial
  82651. */
  82652. SphericalPolynomial.FromArray = function (data) {
  82653. var sp = new SphericalPolynomial();
  82654. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  82655. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  82656. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  82657. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  82658. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  82659. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  82660. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  82661. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  82662. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  82663. return sp;
  82664. };
  82665. return SphericalPolynomial;
  82666. }());
  82667. BABYLON.SphericalPolynomial = SphericalPolynomial;
  82668. /**
  82669. * Class representing spherical harmonics coefficients to the 3rd degree
  82670. */
  82671. var SphericalHarmonics = /** @class */ (function () {
  82672. function SphericalHarmonics() {
  82673. /**
  82674. * The l0,0 coefficients of the spherical harmonics
  82675. */
  82676. this.l00 = BABYLON.Vector3.Zero();
  82677. /**
  82678. * The l1,-1 coefficients of the spherical harmonics
  82679. */
  82680. this.l1_1 = BABYLON.Vector3.Zero();
  82681. /**
  82682. * The l1,0 coefficients of the spherical harmonics
  82683. */
  82684. this.l10 = BABYLON.Vector3.Zero();
  82685. /**
  82686. * The l1,1 coefficients of the spherical harmonics
  82687. */
  82688. this.l11 = BABYLON.Vector3.Zero();
  82689. /**
  82690. * The l2,-2 coefficients of the spherical harmonics
  82691. */
  82692. this.l2_2 = BABYLON.Vector3.Zero();
  82693. /**
  82694. * The l2,-1 coefficients of the spherical harmonics
  82695. */
  82696. this.l2_1 = BABYLON.Vector3.Zero();
  82697. /**
  82698. * The l2,0 coefficients of the spherical harmonics
  82699. */
  82700. this.l20 = BABYLON.Vector3.Zero();
  82701. /**
  82702. * The l2,1 coefficients of the spherical harmonics
  82703. */
  82704. this.l21 = BABYLON.Vector3.Zero();
  82705. /**
  82706. * The l2,2 coefficients of the spherical harmonics
  82707. */
  82708. this.lL22 = BABYLON.Vector3.Zero();
  82709. }
  82710. /**
  82711. * Adds a light to the spherical harmonics
  82712. * @param direction the direction of the light
  82713. * @param color the color of the light
  82714. * @param deltaSolidAngle the delta solid angle of the light
  82715. */
  82716. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  82717. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82718. var c = colorVector.scale(deltaSolidAngle);
  82719. this.l00 = this.l00.add(c.scale(0.282095));
  82720. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  82721. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  82722. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  82723. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  82724. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  82725. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  82726. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  82727. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  82728. };
  82729. /**
  82730. * Scales the spherical harmonics by the given amount
  82731. * @param scale the amount to scale
  82732. */
  82733. SphericalHarmonics.prototype.scale = function (scale) {
  82734. this.l00 = this.l00.scale(scale);
  82735. this.l1_1 = this.l1_1.scale(scale);
  82736. this.l10 = this.l10.scale(scale);
  82737. this.l11 = this.l11.scale(scale);
  82738. this.l2_2 = this.l2_2.scale(scale);
  82739. this.l2_1 = this.l2_1.scale(scale);
  82740. this.l20 = this.l20.scale(scale);
  82741. this.l21 = this.l21.scale(scale);
  82742. this.lL22 = this.lL22.scale(scale);
  82743. };
  82744. /**
  82745. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  82746. *
  82747. * ```
  82748. * E_lm = A_l * L_lm
  82749. * ```
  82750. *
  82751. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  82752. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  82753. * the scaling factors are given in equation 9.
  82754. */
  82755. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  82756. // Constant (Band 0)
  82757. this.l00 = this.l00.scale(3.141593);
  82758. // Linear (Band 1)
  82759. this.l1_1 = this.l1_1.scale(2.094395);
  82760. this.l10 = this.l10.scale(2.094395);
  82761. this.l11 = this.l11.scale(2.094395);
  82762. // Quadratic (Band 2)
  82763. this.l2_2 = this.l2_2.scale(0.785398);
  82764. this.l2_1 = this.l2_1.scale(0.785398);
  82765. this.l20 = this.l20.scale(0.785398);
  82766. this.l21 = this.l21.scale(0.785398);
  82767. this.lL22 = this.lL22.scale(0.785398);
  82768. };
  82769. /**
  82770. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82771. *
  82772. * ```
  82773. * L = (1/pi) * E * rho
  82774. * ```
  82775. *
  82776. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82777. */
  82778. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  82779. this.scale(1.0 / Math.PI);
  82780. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82781. // (The pixel shader must apply albedo after texture fetches, etc).
  82782. };
  82783. /**
  82784. * Gets the spherical harmonics from polynomial
  82785. * @param polynomial the spherical polynomial
  82786. * @returns the spherical harmonics
  82787. */
  82788. SphericalHarmonics.FromPolynomial = function (polynomial) {
  82789. var result = new SphericalHarmonics();
  82790. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  82791. result.l1_1 = polynomial.y.scale(0.977204);
  82792. result.l10 = polynomial.z.scale(0.977204);
  82793. result.l11 = polynomial.x.scale(0.977204);
  82794. result.l2_2 = polynomial.xy.scale(1.16538);
  82795. result.l2_1 = polynomial.yz.scale(1.16538);
  82796. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  82797. result.l21 = polynomial.zx.scale(1.16538);
  82798. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  82799. result.scale(Math.PI);
  82800. return result;
  82801. };
  82802. /**
  82803. * Constructs a spherical harmonics from an array.
  82804. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  82805. * @returns the spherical harmonics
  82806. */
  82807. SphericalHarmonics.FromArray = function (data) {
  82808. var sh = new SphericalHarmonics();
  82809. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  82810. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  82811. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  82812. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  82813. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  82814. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  82815. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  82816. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  82817. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  82818. return sh;
  82819. };
  82820. return SphericalHarmonics;
  82821. }());
  82822. BABYLON.SphericalHarmonics = SphericalHarmonics;
  82823. })(BABYLON || (BABYLON = {}));
  82824. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  82825. var BABYLON;
  82826. (function (BABYLON) {
  82827. var FileFaceOrientation = /** @class */ (function () {
  82828. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  82829. this.name = name;
  82830. this.worldAxisForNormal = worldAxisForNormal;
  82831. this.worldAxisForFileX = worldAxisForFileX;
  82832. this.worldAxisForFileY = worldAxisForFileY;
  82833. }
  82834. return FileFaceOrientation;
  82835. }());
  82836. ;
  82837. /**
  82838. * Helper class dealing with the extraction of spherical polynomial dataArray
  82839. * from a cube map.
  82840. */
  82841. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  82842. function CubeMapToSphericalPolynomialTools() {
  82843. }
  82844. /**
  82845. * Converts a texture to the according Spherical Polynomial data.
  82846. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82847. *
  82848. * @param texture The texture to extract the information from.
  82849. * @return The Spherical Polynomial data.
  82850. */
  82851. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  82852. if (!texture.isCube) {
  82853. // Only supports cube Textures currently.
  82854. return null;
  82855. }
  82856. var size = texture.getSize().width;
  82857. var right = texture.readPixels(0);
  82858. var left = texture.readPixels(1);
  82859. var up;
  82860. var down;
  82861. if (texture.isRenderTarget) {
  82862. up = texture.readPixels(3);
  82863. down = texture.readPixels(2);
  82864. }
  82865. else {
  82866. up = texture.readPixels(2);
  82867. down = texture.readPixels(3);
  82868. }
  82869. var front = texture.readPixels(4);
  82870. var back = texture.readPixels(5);
  82871. var gammaSpace = texture.gammaSpace;
  82872. // Always read as RGBA.
  82873. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82874. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82875. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82876. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82877. }
  82878. var cubeInfo = {
  82879. size: size,
  82880. right: right,
  82881. left: left,
  82882. up: up,
  82883. down: down,
  82884. front: front,
  82885. back: back,
  82886. format: format,
  82887. type: type,
  82888. gammaSpace: gammaSpace,
  82889. };
  82890. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82891. };
  82892. /**
  82893. * Converts a cubemap to the according Spherical Polynomial data.
  82894. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82895. *
  82896. * @param cubeInfo The Cube map to extract the information from.
  82897. * @return The Spherical Polynomial data.
  82898. */
  82899. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82900. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82901. var totalSolidAngle = 0.0;
  82902. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82903. var du = 2.0 / cubeInfo.size;
  82904. var dv = du;
  82905. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82906. var minUV = du * 0.5 - 1.0;
  82907. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82908. var fileFace = this.FileFaces[faceIndex];
  82909. var dataArray = cubeInfo[fileFace.name];
  82910. var v = minUV;
  82911. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82912. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82913. // Because SP is still linear, so summation is fine in that basis.
  82914. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82915. for (var y = 0; y < cubeInfo.size; y++) {
  82916. var u = minUV;
  82917. for (var x = 0; x < cubeInfo.size; x++) {
  82918. // World direction (not normalised)
  82919. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82920. worldDirection.normalize();
  82921. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82922. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82923. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82924. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82925. // Handle Integer types.
  82926. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82927. r /= 255;
  82928. g /= 255;
  82929. b /= 255;
  82930. }
  82931. // Handle Gamma space textures.
  82932. if (cubeInfo.gammaSpace) {
  82933. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82934. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82935. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82936. }
  82937. var color = new BABYLON.Color3(r, g, b);
  82938. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82939. totalSolidAngle += deltaSolidAngle;
  82940. u += du;
  82941. }
  82942. v += dv;
  82943. }
  82944. }
  82945. // Solid angle for entire sphere is 4*pi
  82946. var sphereSolidAngle = 4.0 * Math.PI;
  82947. // Adjust the solid angle to allow for how many faces we processed.
  82948. var facesProcessed = 6.0;
  82949. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82950. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82951. // This is needed because the numerical integration over the cube uses a
  82952. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82953. // and also to compensate for accumulative error due to float precision in the summation.
  82954. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82955. sphericalHarmonics.scale(correctionFactor);
  82956. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82957. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82958. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82959. };
  82960. CubeMapToSphericalPolynomialTools.FileFaces = [
  82961. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82962. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82963. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82964. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82965. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82966. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82967. ];
  82968. return CubeMapToSphericalPolynomialTools;
  82969. }());
  82970. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82971. })(BABYLON || (BABYLON = {}));
  82972. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82973. var BABYLON;
  82974. (function (BABYLON) {
  82975. /**
  82976. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82977. */
  82978. var PanoramaToCubeMapTools = /** @class */ (function () {
  82979. function PanoramaToCubeMapTools() {
  82980. }
  82981. /**
  82982. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82983. *
  82984. * @param float32Array The source data.
  82985. * @param inputWidth The width of the input panorama.
  82986. * @param inputhHeight The height of the input panorama.
  82987. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82988. * @return The cubemap data
  82989. */
  82990. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82991. if (!float32Array) {
  82992. throw "ConvertPanoramaToCubemap: input cannot be null";
  82993. }
  82994. if (float32Array.length != inputWidth * inputHeight * 3) {
  82995. throw "ConvertPanoramaToCubemap: input size is wrong";
  82996. }
  82997. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82998. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82999. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83000. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83001. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83002. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83003. return {
  83004. front: textureFront,
  83005. back: textureBack,
  83006. left: textureLeft,
  83007. right: textureRight,
  83008. up: textureUp,
  83009. down: textureDown,
  83010. size: size,
  83011. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  83012. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  83013. gammaSpace: false,
  83014. };
  83015. };
  83016. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  83017. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  83018. var textureArray = new Float32Array(buffer);
  83019. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  83020. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  83021. var dy = 1 / texSize;
  83022. var fy = 0;
  83023. for (var y = 0; y < texSize; y++) {
  83024. var xv1 = faceData[0];
  83025. var xv2 = faceData[2];
  83026. for (var x = 0; x < texSize; x++) {
  83027. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  83028. v.normalize();
  83029. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  83030. // 3 channels per pixels
  83031. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  83032. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  83033. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  83034. xv1 = xv1.add(rotDX1);
  83035. xv2 = xv2.add(rotDX2);
  83036. }
  83037. fy += dy;
  83038. }
  83039. return textureArray;
  83040. };
  83041. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  83042. var theta = Math.atan2(vDir.z, vDir.x);
  83043. var phi = Math.acos(vDir.y);
  83044. while (theta < -Math.PI)
  83045. theta += 2 * Math.PI;
  83046. while (theta > Math.PI)
  83047. theta -= 2 * Math.PI;
  83048. var dx = theta / Math.PI;
  83049. var dy = phi / Math.PI;
  83050. // recenter.
  83051. dx = dx * 0.5 + 0.5;
  83052. var px = Math.round(dx * inputWidth);
  83053. if (px < 0)
  83054. px = 0;
  83055. else if (px >= inputWidth)
  83056. px = inputWidth - 1;
  83057. var py = Math.round(dy * inputHeight);
  83058. if (py < 0)
  83059. py = 0;
  83060. else if (py >= inputHeight)
  83061. py = inputHeight - 1;
  83062. var inputY = (inputHeight - py - 1);
  83063. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  83064. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  83065. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  83066. return {
  83067. r: r,
  83068. g: g,
  83069. b: b
  83070. };
  83071. };
  83072. PanoramaToCubeMapTools.FACE_FRONT = [
  83073. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83074. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83075. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83076. new BABYLON.Vector3(1.0, 1.0, -1.0)
  83077. ];
  83078. PanoramaToCubeMapTools.FACE_BACK = [
  83079. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83080. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83081. new BABYLON.Vector3(1.0, 1.0, 1.0),
  83082. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  83083. ];
  83084. PanoramaToCubeMapTools.FACE_RIGHT = [
  83085. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83086. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83087. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83088. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83089. ];
  83090. PanoramaToCubeMapTools.FACE_LEFT = [
  83091. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83092. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83093. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83094. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  83095. ];
  83096. PanoramaToCubeMapTools.FACE_DOWN = [
  83097. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83098. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83099. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83100. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83101. ];
  83102. PanoramaToCubeMapTools.FACE_UP = [
  83103. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83104. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83105. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83106. new BABYLON.Vector3(1.0, -1.0, -1.0)
  83107. ];
  83108. return PanoramaToCubeMapTools;
  83109. }());
  83110. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  83111. })(BABYLON || (BABYLON = {}));
  83112. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  83113. var BABYLON;
  83114. (function (BABYLON) {
  83115. ;
  83116. /**
  83117. * This groups tools to convert HDR texture to native colors array.
  83118. */
  83119. var HDRTools = /** @class */ (function () {
  83120. function HDRTools() {
  83121. }
  83122. HDRTools.Ldexp = function (mantissa, exponent) {
  83123. if (exponent > 1023) {
  83124. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83125. }
  83126. if (exponent < -1074) {
  83127. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83128. }
  83129. return mantissa * Math.pow(2, exponent);
  83130. };
  83131. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83132. if (exponent > 0) { /*nonzero pixel*/
  83133. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83134. float32array[index + 0] = red * exponent;
  83135. float32array[index + 1] = green * exponent;
  83136. float32array[index + 2] = blue * exponent;
  83137. }
  83138. else {
  83139. float32array[index + 0] = 0;
  83140. float32array[index + 1] = 0;
  83141. float32array[index + 2] = 0;
  83142. }
  83143. };
  83144. HDRTools.readStringLine = function (uint8array, startIndex) {
  83145. var line = "";
  83146. var character = "";
  83147. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83148. character = String.fromCharCode(uint8array[i]);
  83149. if (character == "\n") {
  83150. break;
  83151. }
  83152. line += character;
  83153. }
  83154. return line;
  83155. };
  83156. /**
  83157. * Reads header information from an RGBE texture stored in a native array.
  83158. * More information on this format are available here:
  83159. * https://en.wikipedia.org/wiki/RGBE_image_format
  83160. *
  83161. * @param uint8array The binary file stored in native array.
  83162. * @return The header information.
  83163. */
  83164. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83165. var height = 0;
  83166. var width = 0;
  83167. var line = this.readStringLine(uint8array, 0);
  83168. if (line[0] != '#' || line[1] != '?') {
  83169. throw "Bad HDR Format.";
  83170. }
  83171. var endOfHeader = false;
  83172. var findFormat = false;
  83173. var lineIndex = 0;
  83174. do {
  83175. lineIndex += (line.length + 1);
  83176. line = this.readStringLine(uint8array, lineIndex);
  83177. if (line == "FORMAT=32-bit_rle_rgbe") {
  83178. findFormat = true;
  83179. }
  83180. else if (line.length == 0) {
  83181. endOfHeader = true;
  83182. }
  83183. } while (!endOfHeader);
  83184. if (!findFormat) {
  83185. throw "HDR Bad header format, unsupported FORMAT";
  83186. }
  83187. lineIndex += (line.length + 1);
  83188. line = this.readStringLine(uint8array, lineIndex);
  83189. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83190. var match = sizeRegexp.exec(line);
  83191. // TODO. Support +Y and -X if needed.
  83192. if (!match || match.length < 3) {
  83193. throw "HDR Bad header format, no size";
  83194. }
  83195. width = parseInt(match[2]);
  83196. height = parseInt(match[1]);
  83197. if (width < 8 || width > 0x7fff) {
  83198. throw "HDR Bad header format, unsupported size";
  83199. }
  83200. lineIndex += (line.length + 1);
  83201. return {
  83202. height: height,
  83203. width: width,
  83204. dataPosition: lineIndex
  83205. };
  83206. };
  83207. /**
  83208. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83209. * This RGBE texture needs to store the information as a panorama.
  83210. *
  83211. * More information on this format are available here:
  83212. * https://en.wikipedia.org/wiki/RGBE_image_format
  83213. *
  83214. * @param buffer The binary file stored in an array buffer.
  83215. * @param size The expected size of the extracted cubemap.
  83216. * @return The Cube Map information.
  83217. */
  83218. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83219. var uint8array = new Uint8Array(buffer);
  83220. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83221. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83222. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83223. return cubeMapData;
  83224. };
  83225. /**
  83226. * Returns the pixels data extracted from an RGBE texture.
  83227. * This pixels will be stored left to right up to down in the R G B order in one array.
  83228. *
  83229. * More information on this format are available here:
  83230. * https://en.wikipedia.org/wiki/RGBE_image_format
  83231. *
  83232. * @param uint8array The binary file stored in an array buffer.
  83233. * @param hdrInfo The header information of the file.
  83234. * @return The pixels data in RGB right to left up to down order.
  83235. */
  83236. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83237. // Keep for multi format supports.
  83238. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83239. };
  83240. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83241. var num_scanlines = hdrInfo.height;
  83242. var scanline_width = hdrInfo.width;
  83243. var a, b, c, d, count;
  83244. var dataIndex = hdrInfo.dataPosition;
  83245. var index = 0, endIndex = 0, i = 0;
  83246. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83247. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83248. // 3 channels of 4 bytes per pixel in float.
  83249. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83250. var resultArray = new Float32Array(resultBuffer);
  83251. // read in each successive scanline
  83252. while (num_scanlines > 0) {
  83253. a = uint8array[dataIndex++];
  83254. b = uint8array[dataIndex++];
  83255. c = uint8array[dataIndex++];
  83256. d = uint8array[dataIndex++];
  83257. if (a != 2 || b != 2 || (c & 0x80)) {
  83258. // this file is not run length encoded
  83259. throw "HDR Bad header format, not RLE";
  83260. }
  83261. if (((c << 8) | d) != scanline_width) {
  83262. throw "HDR Bad header format, wrong scan line width";
  83263. }
  83264. index = 0;
  83265. // read each of the four channels for the scanline into the buffer
  83266. for (i = 0; i < 4; i++) {
  83267. endIndex = (i + 1) * scanline_width;
  83268. while (index < endIndex) {
  83269. a = uint8array[dataIndex++];
  83270. b = uint8array[dataIndex++];
  83271. if (a > 128) {
  83272. // a run of the same value
  83273. count = a - 128;
  83274. if ((count == 0) || (count > endIndex - index)) {
  83275. throw "HDR Bad Format, bad scanline data (run)";
  83276. }
  83277. while (count-- > 0) {
  83278. scanLineArray[index++] = b;
  83279. }
  83280. }
  83281. else {
  83282. // a non-run
  83283. count = a;
  83284. if ((count == 0) || (count > endIndex - index)) {
  83285. throw "HDR Bad Format, bad scanline data (non-run)";
  83286. }
  83287. scanLineArray[index++] = b;
  83288. if (--count > 0) {
  83289. for (var j = 0; j < count; j++) {
  83290. scanLineArray[index++] = uint8array[dataIndex++];
  83291. }
  83292. }
  83293. }
  83294. }
  83295. }
  83296. // now convert data from buffer into floats
  83297. for (i = 0; i < scanline_width; i++) {
  83298. a = scanLineArray[i];
  83299. b = scanLineArray[i + scanline_width];
  83300. c = scanLineArray[i + 2 * scanline_width];
  83301. d = scanLineArray[i + 3 * scanline_width];
  83302. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83303. }
  83304. num_scanlines--;
  83305. }
  83306. return resultArray;
  83307. };
  83308. return HDRTools;
  83309. }());
  83310. BABYLON.HDRTools = HDRTools;
  83311. })(BABYLON || (BABYLON = {}));
  83312. //# sourceMappingURL=babylon.hdr.js.map
  83313. var BABYLON;
  83314. (function (BABYLON) {
  83315. /**
  83316. * Sets of helpers addressing the serialization and deserialization of environment texture
  83317. * stored in a BabylonJS env file.
  83318. * Those files are usually stored as .env files.
  83319. */
  83320. var EnvironmentTextureTools = /** @class */ (function () {
  83321. function EnvironmentTextureTools() {
  83322. }
  83323. /**
  83324. * Gets the environment info from an env file.
  83325. * @param data The array buffer containing the .env bytes.
  83326. * @returns the environment file info (the json header) if successfully parsed.
  83327. */
  83328. EnvironmentTextureTools.GetEnvInfo = function (data) {
  83329. var dataView = new DataView(data);
  83330. var pos = 0;
  83331. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  83332. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  83333. BABYLON.Tools.Error('Not a babylon environment map');
  83334. return null;
  83335. }
  83336. }
  83337. // Read json manifest - collect characters up to null terminator
  83338. var manifestString = '';
  83339. var charCode = 0x00;
  83340. while ((charCode = dataView.getUint8(pos++))) {
  83341. manifestString += String.fromCharCode(charCode);
  83342. }
  83343. var manifest = JSON.parse(manifestString);
  83344. if (manifest.specular) {
  83345. // Extend the header with the position of the payload.
  83346. manifest.specular.specularDataPosition = pos;
  83347. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  83348. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  83349. }
  83350. return manifest;
  83351. };
  83352. /**
  83353. * Creates an environment texture from a loaded cube texture.
  83354. * @param texture defines the cube texture to convert in env file
  83355. * @return a promise containing the environment data if succesfull.
  83356. */
  83357. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  83358. var _this = this;
  83359. var internalTexture = texture.getInternalTexture();
  83360. if (!internalTexture) {
  83361. return Promise.reject("The cube texture is invalid.");
  83362. }
  83363. if (!texture._prefiltered) {
  83364. return Promise.reject("The cube texture is invalid (not prefiltered).");
  83365. }
  83366. var engine = internalTexture.getEngine();
  83367. if (engine && engine.premultipliedAlpha) {
  83368. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  83369. }
  83370. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  83371. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  83372. }
  83373. var canvas = engine.getRenderingCanvas();
  83374. if (!canvas) {
  83375. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  83376. }
  83377. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83378. if (!engine.getCaps().textureFloatRender) {
  83379. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83380. if (!engine.getCaps().textureHalfFloatRender) {
  83381. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  83382. }
  83383. }
  83384. var cubeWidth = internalTexture.width;
  83385. var hostingScene = new BABYLON.Scene(engine);
  83386. var specularTextures = {};
  83387. var promises = [];
  83388. // Read and collect all mipmaps data from the cube.
  83389. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  83390. mipmapsCount = Math.round(mipmapsCount);
  83391. var _loop_1 = function (i) {
  83392. var faceWidth = Math.pow(2, mipmapsCount - i);
  83393. var _loop_2 = function (face) {
  83394. var data = texture.readPixels(face, i);
  83395. // Creates a temp texture with the face data.
  83396. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  83397. // And rgbdEncode them.
  83398. var promise = new Promise(function (resolve, reject) {
  83399. 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);
  83400. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83401. rgbdPostProcess.onApply = function (effect) {
  83402. effect._bindTexture("textureSampler", tempTexture);
  83403. };
  83404. // As the process needs to happen on the main canvas, keep track of the current size
  83405. var currentW = engine.getRenderWidth();
  83406. var currentH = engine.getRenderHeight();
  83407. // Set the desired size for the texture
  83408. engine.setSize(faceWidth, faceWidth);
  83409. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  83410. // Reading datas from WebGL
  83411. BABYLON.Tools.ToBlob(canvas, function (blob) {
  83412. var fileReader = new FileReader();
  83413. fileReader.onload = function (event) {
  83414. var arrayBuffer = event.target.result;
  83415. specularTextures[i * 6 + face] = arrayBuffer;
  83416. resolve();
  83417. };
  83418. fileReader.readAsArrayBuffer(blob);
  83419. });
  83420. // Reapply the previous canvas size
  83421. engine.setSize(currentW, currentH);
  83422. });
  83423. });
  83424. promises.push(promise);
  83425. };
  83426. // All faces of the cube.
  83427. for (var face = 0; face < 6; face++) {
  83428. _loop_2(face);
  83429. }
  83430. };
  83431. for (var i = 0; i <= mipmapsCount; i++) {
  83432. _loop_1(i);
  83433. }
  83434. // Once all the textures haves been collected as RGBD stored in PNGs
  83435. return Promise.all(promises).then(function () {
  83436. // We can delete the hosting scene keeping track of all the creation objects
  83437. hostingScene.dispose();
  83438. // Creates the json header for the env texture
  83439. var info = {
  83440. version: 1,
  83441. width: cubeWidth,
  83442. irradiance: _this._CreateEnvTextureIrradiance(texture),
  83443. specular: {
  83444. mipmaps: [],
  83445. lodGenerationScale: texture.lodGenerationScale
  83446. }
  83447. };
  83448. // Sets the specular image data information
  83449. var position = 0;
  83450. for (var i = 0; i <= mipmapsCount; i++) {
  83451. for (var face = 0; face < 6; face++) {
  83452. var byteLength = specularTextures[i * 6 + face].byteLength;
  83453. info.specular.mipmaps.push({
  83454. length: byteLength,
  83455. position: position
  83456. });
  83457. position += byteLength;
  83458. }
  83459. }
  83460. // Encode the JSON as an array buffer
  83461. var infoString = JSON.stringify(info);
  83462. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  83463. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  83464. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  83465. infoView[i] = infoString.charCodeAt(i);
  83466. }
  83467. // Ends up with a null terminator for easier parsing
  83468. infoView[infoString.length] = 0x00;
  83469. // Computes the final required size and creates the storage
  83470. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  83471. var finalBuffer = new ArrayBuffer(totalSize);
  83472. var finalBufferView = new Uint8Array(finalBuffer);
  83473. var dataView = new DataView(finalBuffer);
  83474. // Copy the magic bytes identifying the file in
  83475. var pos = 0;
  83476. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  83477. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  83478. }
  83479. // Add the json info
  83480. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  83481. pos += infoBuffer.byteLength;
  83482. // Finally inserts the texture data
  83483. for (var i = 0; i <= mipmapsCount; i++) {
  83484. for (var face = 0; face < 6; face++) {
  83485. var dataBuffer = specularTextures[i * 6 + face];
  83486. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  83487. pos += dataBuffer.byteLength;
  83488. }
  83489. }
  83490. // Voila
  83491. return finalBuffer;
  83492. });
  83493. };
  83494. /**
  83495. * Creates a JSON representation of the spherical data.
  83496. * @param texture defines the texture containing the polynomials
  83497. * @return the JSON representation of the spherical info
  83498. */
  83499. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  83500. var polynmials = texture.sphericalPolynomial;
  83501. if (polynmials == null) {
  83502. return null;
  83503. }
  83504. return {
  83505. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  83506. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  83507. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  83508. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  83509. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  83510. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  83511. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  83512. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  83513. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  83514. };
  83515. };
  83516. /**
  83517. * Uploads the texture info contained in the env file to the GPU.
  83518. * @param texture defines the internal texture to upload to
  83519. * @param arrayBuffer defines the buffer cotaining the data to load
  83520. * @param info defines the texture info retrieved through the GetEnvInfo method
  83521. * @returns a promise
  83522. */
  83523. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  83524. if (info.version !== 1) {
  83525. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  83526. }
  83527. var specularInfo = info.specular;
  83528. if (!specularInfo) {
  83529. // Nothing else parsed so far
  83530. return Promise.resolve();
  83531. }
  83532. // Double checks the enclosed info
  83533. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  83534. mipmapsCount = Math.round(mipmapsCount) + 1;
  83535. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  83536. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  83537. }
  83538. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  83539. var imageData = new Array(mipmapsCount);
  83540. for (var i = 0; i < mipmapsCount; i++) {
  83541. imageData[i] = new Array(6);
  83542. for (var face = 0; face < 6; face++) {
  83543. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  83544. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  83545. }
  83546. }
  83547. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  83548. };
  83549. /**
  83550. * Uploads the levels of image data to the GPU.
  83551. * @param texture defines the internal texture to upload to
  83552. * @param imageData defines the array buffer views of image data [mipmap][face]
  83553. * @returns a promise
  83554. */
  83555. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  83556. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  83557. throw new Error("Texture size must be a power of two");
  83558. }
  83559. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  83560. // Gets everything ready.
  83561. var engine = texture.getEngine();
  83562. var expandTexture = false;
  83563. var generateNonLODTextures = false;
  83564. var rgbdPostProcess = null;
  83565. var cubeRtt = null;
  83566. var lodTextures = null;
  83567. var caps = engine.getCaps();
  83568. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  83569. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83570. texture.generateMipMaps = true;
  83571. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  83572. // Add extra process if texture lod is not supported
  83573. if (!caps.textureLOD) {
  83574. expandTexture = false;
  83575. generateNonLODTextures = true;
  83576. lodTextures = {};
  83577. }
  83578. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  83579. else if (engine.webGLVersion < 2) {
  83580. expandTexture = false;
  83581. }
  83582. // If half float available we can uncompress the texture
  83583. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  83584. expandTexture = true;
  83585. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83586. }
  83587. // If full float available we can uncompress the texture
  83588. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  83589. expandTexture = true;
  83590. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83591. }
  83592. // Expand the texture if possible
  83593. if (expandTexture) {
  83594. // Simply run through the decode PP
  83595. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  83596. texture._isRGBD = false;
  83597. texture.invertY = false;
  83598. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  83599. generateDepthBuffer: false,
  83600. generateMipMaps: true,
  83601. generateStencilBuffer: false,
  83602. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  83603. type: texture.type,
  83604. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  83605. });
  83606. }
  83607. else {
  83608. texture._isRGBD = true;
  83609. texture.invertY = true;
  83610. // In case of missing support, applies the same patch than DDS files.
  83611. if (generateNonLODTextures) {
  83612. var mipSlices = 3;
  83613. var scale = texture._lodGenerationScale;
  83614. var offset = texture._lodGenerationOffset;
  83615. for (var i = 0; i < mipSlices; i++) {
  83616. //compute LOD from even spacing in smoothness (matching shader calculation)
  83617. var smoothness = i / (mipSlices - 1);
  83618. var roughness = 1 - smoothness;
  83619. var minLODIndex = offset; // roughness = 0
  83620. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  83621. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  83622. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  83623. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  83624. glTextureFromLod.isCube = true;
  83625. glTextureFromLod.invertY = true;
  83626. glTextureFromLod.generateMipMaps = false;
  83627. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  83628. // Wrap in a base texture for easy binding.
  83629. var lodTexture = new BABYLON.BaseTexture(null);
  83630. lodTexture.isCube = true;
  83631. lodTexture._texture = glTextureFromLod;
  83632. lodTextures[mipmapIndex] = lodTexture;
  83633. switch (i) {
  83634. case 0:
  83635. texture._lodTextureLow = lodTexture;
  83636. break;
  83637. case 1:
  83638. texture._lodTextureMid = lodTexture;
  83639. break;
  83640. case 2:
  83641. texture._lodTextureHigh = lodTexture;
  83642. break;
  83643. }
  83644. }
  83645. }
  83646. }
  83647. var promises = [];
  83648. var _loop_3 = function (i) {
  83649. var _loop_4 = function (face) {
  83650. // Constructs an image element from image data
  83651. var bytes = imageData[i][face];
  83652. var blob = new Blob([bytes], { type: 'image/png' });
  83653. var url = URL.createObjectURL(blob);
  83654. var image = new Image();
  83655. image.src = url;
  83656. // Enqueue promise to upload to the texture.
  83657. var promise = new Promise(function (resolve, reject) {
  83658. image.onload = function () {
  83659. if (expandTexture) {
  83660. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  83661. reject(message);
  83662. }, image);
  83663. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83664. // Uncompress the data to a RTT
  83665. rgbdPostProcess.onApply = function (effect) {
  83666. effect._bindTexture("textureSampler", tempTexture_1);
  83667. effect.setFloat2("scale", 1, 1);
  83668. };
  83669. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  83670. // Cleanup
  83671. engine.restoreDefaultFramebuffer();
  83672. tempTexture_1.dispose();
  83673. window.URL.revokeObjectURL(url);
  83674. resolve();
  83675. });
  83676. }
  83677. else {
  83678. engine._uploadImageToTexture(texture, image, face, i);
  83679. // Upload the face to the non lod texture support
  83680. if (generateNonLODTextures) {
  83681. var lodTexture = lodTextures[i];
  83682. if (lodTexture) {
  83683. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  83684. }
  83685. }
  83686. resolve();
  83687. }
  83688. };
  83689. image.onerror = function (error) {
  83690. reject(error);
  83691. };
  83692. });
  83693. promises.push(promise);
  83694. };
  83695. // All faces
  83696. for (var face = 0; face < 6; face++) {
  83697. _loop_4(face);
  83698. }
  83699. };
  83700. // All mipmaps up to provided number of images
  83701. for (var i = 0; i < imageData.length; i++) {
  83702. _loop_3(i);
  83703. }
  83704. // Fill remaining mipmaps with black textures.
  83705. if (imageData.length < mipmapsCount) {
  83706. var data = void 0;
  83707. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  83708. var dataLength = size * size * 4;
  83709. switch (texture.type) {
  83710. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  83711. data = new Uint8Array(dataLength);
  83712. break;
  83713. }
  83714. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  83715. data = new Uint16Array(dataLength);
  83716. break;
  83717. }
  83718. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  83719. data = new Float32Array(dataLength);
  83720. break;
  83721. }
  83722. }
  83723. for (var i = imageData.length; i < mipmapsCount; i++) {
  83724. for (var face = 0; face < 6; face++) {
  83725. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  83726. }
  83727. }
  83728. }
  83729. // Once all done, finishes the cleanup and return
  83730. return Promise.all(promises).then(function () {
  83731. // Release temp RTT.
  83732. if (cubeRtt) {
  83733. engine._releaseFramebufferObjects(cubeRtt);
  83734. cubeRtt._swapAndDie(texture);
  83735. }
  83736. // Release temp Post Process.
  83737. if (rgbdPostProcess) {
  83738. rgbdPostProcess.dispose();
  83739. }
  83740. // Flag internal texture as ready in case they are in use.
  83741. if (generateNonLODTextures) {
  83742. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  83743. texture._lodTextureHigh._texture.isReady = true;
  83744. }
  83745. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  83746. texture._lodTextureMid._texture.isReady = true;
  83747. }
  83748. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  83749. texture._lodTextureLow._texture.isReady = true;
  83750. }
  83751. }
  83752. });
  83753. };
  83754. /**
  83755. * Uploads spherical polynomials information to the texture.
  83756. * @param texture defines the texture we are trying to upload the information to
  83757. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  83758. */
  83759. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  83760. if (info.version !== 1) {
  83761. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  83762. }
  83763. var irradianceInfo = info.irradiance;
  83764. if (!irradianceInfo) {
  83765. return;
  83766. }
  83767. var sp = new BABYLON.SphericalPolynomial();
  83768. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  83769. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  83770. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  83771. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  83772. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  83773. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  83774. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  83775. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  83776. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  83777. texture._sphericalPolynomial = sp;
  83778. };
  83779. /**
  83780. * Magic number identifying the env file.
  83781. */
  83782. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  83783. return EnvironmentTextureTools;
  83784. }());
  83785. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  83786. })(BABYLON || (BABYLON = {}));
  83787. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  83788. var BABYLON;
  83789. (function (BABYLON) {
  83790. /**
  83791. * This represents a texture coming from an HDR input.
  83792. *
  83793. * The only supported format is currently panorama picture stored in RGBE format.
  83794. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83795. */
  83796. var HDRCubeTexture = /** @class */ (function (_super) {
  83797. __extends(HDRCubeTexture, _super);
  83798. /**
  83799. * Instantiates an HDRTexture from the following parameters.
  83800. *
  83801. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83802. * @param scene The scene the texture will be used in
  83803. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83804. * @param noMipmap Forces to not generate the mipmap if true
  83805. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83806. * @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)
  83807. * @param reserved Reserved flag for internal use.
  83808. */
  83809. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83810. if (noMipmap === void 0) { noMipmap = false; }
  83811. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83812. if (gammaSpace === void 0) { gammaSpace = false; }
  83813. if (reserved === void 0) { reserved = false; }
  83814. if (onLoad === void 0) { onLoad = null; }
  83815. if (onError === void 0) { onError = null; }
  83816. var _this = _super.call(this, scene) || this;
  83817. _this._generateHarmonics = true;
  83818. _this._onLoad = null;
  83819. _this._onError = null;
  83820. /**
  83821. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83822. */
  83823. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83824. _this._isBlocking = true;
  83825. _this._rotationY = 0;
  83826. /**
  83827. * Gets or sets the center of the bounding box associated with the cube texture
  83828. * It must define where the camera used to render the texture was set
  83829. */
  83830. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83831. if (!url) {
  83832. return _this;
  83833. }
  83834. _this.name = url;
  83835. _this.url = url;
  83836. _this.hasAlpha = false;
  83837. _this.isCube = true;
  83838. _this._textureMatrix = BABYLON.Matrix.Identity();
  83839. _this._onLoad = onLoad;
  83840. _this._onError = onError;
  83841. _this.gammaSpace = gammaSpace;
  83842. _this._noMipmap = noMipmap;
  83843. _this._size = size;
  83844. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83845. if (!_this._texture) {
  83846. if (!scene.useDelayedTextureLoading) {
  83847. _this.loadTexture();
  83848. }
  83849. else {
  83850. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83851. }
  83852. }
  83853. return _this;
  83854. }
  83855. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83856. /**
  83857. * Gets wether or not the texture is blocking during loading.
  83858. */
  83859. get: function () {
  83860. return this._isBlocking;
  83861. },
  83862. /**
  83863. * Sets wether or not the texture is blocking during loading.
  83864. */
  83865. set: function (value) {
  83866. this._isBlocking = value;
  83867. },
  83868. enumerable: true,
  83869. configurable: true
  83870. });
  83871. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83872. /**
  83873. * Gets texture matrix rotation angle around Y axis radians.
  83874. */
  83875. get: function () {
  83876. return this._rotationY;
  83877. },
  83878. /**
  83879. * Sets texture matrix rotation angle around Y axis in radians.
  83880. */
  83881. set: function (value) {
  83882. this._rotationY = value;
  83883. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83884. },
  83885. enumerable: true,
  83886. configurable: true
  83887. });
  83888. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83889. get: function () {
  83890. return this._boundingBoxSize;
  83891. },
  83892. /**
  83893. * Gets or sets the size of the bounding box associated with the cube texture
  83894. * When defined, the cubemap will switch to local mode
  83895. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83896. * @example https://www.babylonjs-playground.com/#RNASML
  83897. */
  83898. set: function (value) {
  83899. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83900. return;
  83901. }
  83902. this._boundingBoxSize = value;
  83903. var scene = this.getScene();
  83904. if (scene) {
  83905. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83906. }
  83907. },
  83908. enumerable: true,
  83909. configurable: true
  83910. });
  83911. /**
  83912. * Occurs when the file is raw .hdr file.
  83913. */
  83914. HDRCubeTexture.prototype.loadTexture = function () {
  83915. var _this = this;
  83916. var callback = function (buffer) {
  83917. _this.lodGenerationOffset = 0.0;
  83918. _this.lodGenerationScale = 0.8;
  83919. var scene = _this.getScene();
  83920. if (!scene) {
  83921. return null;
  83922. }
  83923. // Extract the raw linear data.
  83924. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83925. // Generate harmonics if needed.
  83926. if (_this._generateHarmonics) {
  83927. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83928. _this.sphericalPolynomial = sphericalPolynomial;
  83929. }
  83930. var results = [];
  83931. var byteArray = null;
  83932. // Push each faces.
  83933. for (var j = 0; j < 6; j++) {
  83934. // Create uintarray fallback.
  83935. if (!scene.getEngine().getCaps().textureFloat) {
  83936. // 3 channels of 1 bytes per pixel in bytes.
  83937. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83938. byteArray = new Uint8Array(byteBuffer);
  83939. }
  83940. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83941. // If special cases.
  83942. if (_this.gammaSpace || byteArray) {
  83943. for (var i = 0; i < _this._size * _this._size; i++) {
  83944. // Put in gamma space if requested.
  83945. if (_this.gammaSpace) {
  83946. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83947. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83948. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83949. }
  83950. // Convert to int texture for fallback.
  83951. if (byteArray) {
  83952. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83953. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83954. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83955. // May use luminance instead if the result is not accurate.
  83956. var max = Math.max(Math.max(r, g), b);
  83957. if (max > 255) {
  83958. var scale = 255 / max;
  83959. r *= scale;
  83960. g *= scale;
  83961. b *= scale;
  83962. }
  83963. byteArray[(i * 3) + 0] = r;
  83964. byteArray[(i * 3) + 1] = g;
  83965. byteArray[(i * 3) + 2] = b;
  83966. }
  83967. }
  83968. }
  83969. if (byteArray) {
  83970. results.push(byteArray);
  83971. }
  83972. else {
  83973. results.push(dataFace);
  83974. }
  83975. }
  83976. return results;
  83977. };
  83978. var scene = this.getScene();
  83979. if (scene) {
  83980. 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);
  83981. }
  83982. };
  83983. HDRCubeTexture.prototype.clone = function () {
  83984. var scene = this.getScene();
  83985. if (!scene) {
  83986. return this;
  83987. }
  83988. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83989. // Base texture
  83990. newTexture.level = this.level;
  83991. newTexture.wrapU = this.wrapU;
  83992. newTexture.wrapV = this.wrapV;
  83993. newTexture.coordinatesIndex = this.coordinatesIndex;
  83994. newTexture.coordinatesMode = this.coordinatesMode;
  83995. return newTexture;
  83996. };
  83997. // Methods
  83998. HDRCubeTexture.prototype.delayLoad = function () {
  83999. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84000. return;
  84001. }
  84002. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84003. this._texture = this._getFromCache(this.url, this._noMipmap);
  84004. if (!this._texture) {
  84005. this.loadTexture();
  84006. }
  84007. };
  84008. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  84009. return this._textureMatrix;
  84010. };
  84011. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  84012. this._textureMatrix = value;
  84013. };
  84014. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84015. var texture = null;
  84016. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84017. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  84018. texture.name = parsedTexture.name;
  84019. texture.hasAlpha = parsedTexture.hasAlpha;
  84020. texture.level = parsedTexture.level;
  84021. texture.coordinatesMode = parsedTexture.coordinatesMode;
  84022. texture.isBlocking = parsedTexture.isBlocking;
  84023. }
  84024. if (texture) {
  84025. if (parsedTexture.boundingBoxPosition) {
  84026. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  84027. }
  84028. if (parsedTexture.boundingBoxSize) {
  84029. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  84030. }
  84031. if (parsedTexture.rotationY) {
  84032. texture.rotationY = parsedTexture.rotationY;
  84033. }
  84034. }
  84035. return texture;
  84036. };
  84037. HDRCubeTexture.prototype.serialize = function () {
  84038. if (!this.name) {
  84039. return null;
  84040. }
  84041. var serializationObject = {};
  84042. serializationObject.name = this.name;
  84043. serializationObject.hasAlpha = this.hasAlpha;
  84044. serializationObject.isCube = true;
  84045. serializationObject.level = this.level;
  84046. serializationObject.size = this._size;
  84047. serializationObject.coordinatesMode = this.coordinatesMode;
  84048. serializationObject.useInGammaSpace = this.gammaSpace;
  84049. serializationObject.generateHarmonics = this._generateHarmonics;
  84050. serializationObject.customType = "BABYLON.HDRCubeTexture";
  84051. serializationObject.noMipmap = this._noMipmap;
  84052. serializationObject.isBlocking = this._isBlocking;
  84053. serializationObject.rotationY = this._rotationY;
  84054. return serializationObject;
  84055. };
  84056. HDRCubeTexture._facesMapping = [
  84057. "right",
  84058. "left",
  84059. "up",
  84060. "down",
  84061. "front",
  84062. "back"
  84063. ];
  84064. return HDRCubeTexture;
  84065. }(BABYLON.BaseTexture));
  84066. BABYLON.HDRCubeTexture = HDRCubeTexture;
  84067. })(BABYLON || (BABYLON = {}));
  84068. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  84069. var BABYLON;
  84070. (function (BABYLON) {
  84071. var IndexedVector2 = /** @class */ (function (_super) {
  84072. __extends(IndexedVector2, _super);
  84073. function IndexedVector2(original, index) {
  84074. var _this = _super.call(this, original.x, original.y) || this;
  84075. _this.index = index;
  84076. return _this;
  84077. }
  84078. return IndexedVector2;
  84079. }(BABYLON.Vector2));
  84080. var PolygonPoints = /** @class */ (function () {
  84081. function PolygonPoints() {
  84082. this.elements = new Array();
  84083. }
  84084. PolygonPoints.prototype.add = function (originalPoints) {
  84085. var _this = this;
  84086. var result = new Array();
  84087. originalPoints.forEach(function (point) {
  84088. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  84089. var newPoint = new IndexedVector2(point, _this.elements.length);
  84090. result.push(newPoint);
  84091. _this.elements.push(newPoint);
  84092. }
  84093. });
  84094. return result;
  84095. };
  84096. PolygonPoints.prototype.computeBounds = function () {
  84097. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84098. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84099. this.elements.forEach(function (point) {
  84100. // x
  84101. if (point.x < lmin.x) {
  84102. lmin.x = point.x;
  84103. }
  84104. else if (point.x > lmax.x) {
  84105. lmax.x = point.x;
  84106. }
  84107. // y
  84108. if (point.y < lmin.y) {
  84109. lmin.y = point.y;
  84110. }
  84111. else if (point.y > lmax.y) {
  84112. lmax.y = point.y;
  84113. }
  84114. });
  84115. return {
  84116. min: lmin,
  84117. max: lmax,
  84118. width: lmax.x - lmin.x,
  84119. height: lmax.y - lmin.y
  84120. };
  84121. };
  84122. return PolygonPoints;
  84123. }());
  84124. var Polygon = /** @class */ (function () {
  84125. function Polygon() {
  84126. }
  84127. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  84128. return [
  84129. new BABYLON.Vector2(xmin, ymin),
  84130. new BABYLON.Vector2(xmax, ymin),
  84131. new BABYLON.Vector2(xmax, ymax),
  84132. new BABYLON.Vector2(xmin, ymax)
  84133. ];
  84134. };
  84135. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  84136. if (cx === void 0) { cx = 0; }
  84137. if (cy === void 0) { cy = 0; }
  84138. if (numberOfSides === void 0) { numberOfSides = 32; }
  84139. var result = new Array();
  84140. var angle = 0;
  84141. var increment = (Math.PI * 2) / numberOfSides;
  84142. for (var i = 0; i < numberOfSides; i++) {
  84143. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  84144. angle -= increment;
  84145. }
  84146. return result;
  84147. };
  84148. Polygon.Parse = function (input) {
  84149. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  84150. var i, result = [];
  84151. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  84152. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  84153. }
  84154. return result;
  84155. };
  84156. Polygon.StartingAt = function (x, y) {
  84157. return BABYLON.Path2.StartingAt(x, y);
  84158. };
  84159. return Polygon;
  84160. }());
  84161. BABYLON.Polygon = Polygon;
  84162. var PolygonMeshBuilder = /** @class */ (function () {
  84163. function PolygonMeshBuilder(name, contours, scene) {
  84164. this._points = new PolygonPoints();
  84165. this._outlinepoints = new PolygonPoints();
  84166. this._holes = new Array();
  84167. this._epoints = new Array();
  84168. this._eholes = new Array();
  84169. this._name = name;
  84170. this._scene = scene;
  84171. var points;
  84172. if (contours instanceof BABYLON.Path2) {
  84173. points = contours.getPoints();
  84174. }
  84175. else {
  84176. points = contours;
  84177. }
  84178. this._addToepoint(points);
  84179. this._points.add(points);
  84180. this._outlinepoints.add(points);
  84181. if (typeof earcut === 'undefined') {
  84182. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  84183. }
  84184. }
  84185. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  84186. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  84187. var p = points_1[_i];
  84188. this._epoints.push(p.x, p.y);
  84189. }
  84190. };
  84191. PolygonMeshBuilder.prototype.addHole = function (hole) {
  84192. this._points.add(hole);
  84193. var holepoints = new PolygonPoints();
  84194. holepoints.add(hole);
  84195. this._holes.push(holepoints);
  84196. this._eholes.push(this._epoints.length / 2);
  84197. this._addToepoint(hole);
  84198. return this;
  84199. };
  84200. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  84201. var _this = this;
  84202. if (updatable === void 0) { updatable = false; }
  84203. if (depth === void 0) { depth = 0; }
  84204. var result = new BABYLON.Mesh(this._name, this._scene);
  84205. var normals = new Array();
  84206. var positions = new Array();
  84207. var uvs = new Array();
  84208. var bounds = this._points.computeBounds();
  84209. this._points.elements.forEach(function (p) {
  84210. normals.push(0, 1.0, 0);
  84211. positions.push(p.x, 0, p.y);
  84212. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  84213. });
  84214. var indices = new Array();
  84215. var res = earcut(this._epoints, this._eholes, 2);
  84216. for (var i = 0; i < res.length; i++) {
  84217. indices.push(res[i]);
  84218. }
  84219. if (depth > 0) {
  84220. var positionscount = (positions.length / 3); //get the current pointcount
  84221. this._points.elements.forEach(function (p) {
  84222. normals.push(0, -1.0, 0);
  84223. positions.push(p.x, -depth, p.y);
  84224. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  84225. });
  84226. var totalCount = indices.length;
  84227. for (var i = 0; i < totalCount; i += 3) {
  84228. var i0 = indices[i + 0];
  84229. var i1 = indices[i + 1];
  84230. var i2 = indices[i + 2];
  84231. indices.push(i2 + positionscount);
  84232. indices.push(i1 + positionscount);
  84233. indices.push(i0 + positionscount);
  84234. }
  84235. //Add the sides
  84236. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  84237. this._holes.forEach(function (hole) {
  84238. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  84239. });
  84240. }
  84241. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  84242. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  84243. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  84244. result.setIndices(indices);
  84245. return result;
  84246. };
  84247. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  84248. var StartIndex = positions.length / 3;
  84249. var ulength = 0;
  84250. for (var i = 0; i < points.elements.length; i++) {
  84251. var p = points.elements[i];
  84252. var p1;
  84253. if ((i + 1) > points.elements.length - 1) {
  84254. p1 = points.elements[0];
  84255. }
  84256. else {
  84257. p1 = points.elements[i + 1];
  84258. }
  84259. positions.push(p.x, 0, p.y);
  84260. positions.push(p.x, -depth, p.y);
  84261. positions.push(p1.x, 0, p1.y);
  84262. positions.push(p1.x, -depth, p1.y);
  84263. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  84264. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  84265. var v3 = v2.subtract(v1);
  84266. var v4 = new BABYLON.Vector3(0, 1, 0);
  84267. var vn = BABYLON.Vector3.Cross(v3, v4);
  84268. vn = vn.normalize();
  84269. uvs.push(ulength / bounds.width, 0);
  84270. uvs.push(ulength / bounds.width, 1);
  84271. ulength += v3.length();
  84272. uvs.push((ulength / bounds.width), 0);
  84273. uvs.push((ulength / bounds.width), 1);
  84274. if (!flip) {
  84275. normals.push(-vn.x, -vn.y, -vn.z);
  84276. normals.push(-vn.x, -vn.y, -vn.z);
  84277. normals.push(-vn.x, -vn.y, -vn.z);
  84278. normals.push(-vn.x, -vn.y, -vn.z);
  84279. indices.push(StartIndex);
  84280. indices.push(StartIndex + 1);
  84281. indices.push(StartIndex + 2);
  84282. indices.push(StartIndex + 1);
  84283. indices.push(StartIndex + 3);
  84284. indices.push(StartIndex + 2);
  84285. }
  84286. else {
  84287. normals.push(vn.x, vn.y, vn.z);
  84288. normals.push(vn.x, vn.y, vn.z);
  84289. normals.push(vn.x, vn.y, vn.z);
  84290. normals.push(vn.x, vn.y, vn.z);
  84291. indices.push(StartIndex);
  84292. indices.push(StartIndex + 2);
  84293. indices.push(StartIndex + 1);
  84294. indices.push(StartIndex + 1);
  84295. indices.push(StartIndex + 2);
  84296. indices.push(StartIndex + 3);
  84297. }
  84298. StartIndex += 4;
  84299. }
  84300. ;
  84301. };
  84302. return PolygonMeshBuilder;
  84303. }());
  84304. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  84305. })(BABYLON || (BABYLON = {}));
  84306. //# sourceMappingURL=babylon.polygonMesh.js.map
  84307. var BABYLON;
  84308. (function (BABYLON) {
  84309. // Unique ID when we import meshes from Babylon to CSG
  84310. var currentCSGMeshId = 0;
  84311. // # class Vertex
  84312. // Represents a vertex of a polygon. Use your own vertex class instead of this
  84313. // one to provide additional features like texture coordinates and vertex
  84314. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  84315. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  84316. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  84317. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  84318. // is not used anywhere else.
  84319. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  84320. var Vertex = /** @class */ (function () {
  84321. function Vertex(pos, normal, uv) {
  84322. this.pos = pos;
  84323. this.normal = normal;
  84324. this.uv = uv;
  84325. }
  84326. Vertex.prototype.clone = function () {
  84327. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  84328. };
  84329. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  84330. // orientation of a polygon is flipped.
  84331. Vertex.prototype.flip = function () {
  84332. this.normal = this.normal.scale(-1);
  84333. };
  84334. // Create a new vertex between this vertex and `other` by linearly
  84335. // interpolating all properties using a parameter of `t`. Subclasses should
  84336. // override this to interpolate additional properties.
  84337. Vertex.prototype.interpolate = function (other, t) {
  84338. 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));
  84339. };
  84340. return Vertex;
  84341. }());
  84342. // # class Plane
  84343. // Represents a plane in 3D space.
  84344. var Plane = /** @class */ (function () {
  84345. function Plane(normal, w) {
  84346. this.normal = normal;
  84347. this.w = w;
  84348. }
  84349. Plane.FromPoints = function (a, b, c) {
  84350. var v0 = c.subtract(a);
  84351. var v1 = b.subtract(a);
  84352. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  84353. return null;
  84354. }
  84355. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  84356. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  84357. };
  84358. Plane.prototype.clone = function () {
  84359. return new Plane(this.normal.clone(), this.w);
  84360. };
  84361. Plane.prototype.flip = function () {
  84362. this.normal.scaleInPlace(-1);
  84363. this.w = -this.w;
  84364. };
  84365. // Split `polygon` by this plane if needed, then put the polygon or polygon
  84366. // fragments in the appropriate lists. Coplanar polygons go into either
  84367. // `coplanarFront` or `coplanarBack` depending on their orientation with
  84368. // respect to this plane. Polygons in front or in back of this plane go into
  84369. // either `front` or `back`.
  84370. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  84371. var COPLANAR = 0;
  84372. var FRONT = 1;
  84373. var BACK = 2;
  84374. var SPANNING = 3;
  84375. // Classify each point as well as the entire polygon into one of the above
  84376. // four classes.
  84377. var polygonType = 0;
  84378. var types = [];
  84379. var i;
  84380. var t;
  84381. for (i = 0; i < polygon.vertices.length; i++) {
  84382. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  84383. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  84384. polygonType |= type;
  84385. types.push(type);
  84386. }
  84387. // Put the polygon in the correct list, splitting it when necessary.
  84388. switch (polygonType) {
  84389. case COPLANAR:
  84390. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  84391. break;
  84392. case FRONT:
  84393. front.push(polygon);
  84394. break;
  84395. case BACK:
  84396. back.push(polygon);
  84397. break;
  84398. case SPANNING:
  84399. var f = [], b = [];
  84400. for (i = 0; i < polygon.vertices.length; i++) {
  84401. var j = (i + 1) % polygon.vertices.length;
  84402. var ti = types[i], tj = types[j];
  84403. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  84404. if (ti !== BACK)
  84405. f.push(vi);
  84406. if (ti !== FRONT)
  84407. b.push(ti !== BACK ? vi.clone() : vi);
  84408. if ((ti | tj) === SPANNING) {
  84409. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  84410. var v = vi.interpolate(vj, t);
  84411. f.push(v);
  84412. b.push(v.clone());
  84413. }
  84414. }
  84415. var poly;
  84416. if (f.length >= 3) {
  84417. poly = new Polygon(f, polygon.shared);
  84418. if (poly.plane)
  84419. front.push(poly);
  84420. }
  84421. if (b.length >= 3) {
  84422. poly = new Polygon(b, polygon.shared);
  84423. if (poly.plane)
  84424. back.push(poly);
  84425. }
  84426. break;
  84427. }
  84428. };
  84429. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  84430. // point is on the plane.
  84431. Plane.EPSILON = 1e-5;
  84432. return Plane;
  84433. }());
  84434. // # class Polygon
  84435. // Represents a convex polygon. The vertices used to initialize a polygon must
  84436. // be coplanar and form a convex loop.
  84437. //
  84438. // Each convex polygon has a `shared` property, which is shared between all
  84439. // polygons that are clones of each other or were split from the same polygon.
  84440. // This can be used to define per-polygon properties (such as surface color).
  84441. var Polygon = /** @class */ (function () {
  84442. function Polygon(vertices, shared) {
  84443. this.vertices = vertices;
  84444. this.shared = shared;
  84445. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84446. }
  84447. Polygon.prototype.clone = function () {
  84448. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84449. return new Polygon(vertices, this.shared);
  84450. };
  84451. Polygon.prototype.flip = function () {
  84452. this.vertices.reverse().map(function (v) { v.flip(); });
  84453. this.plane.flip();
  84454. };
  84455. return Polygon;
  84456. }());
  84457. // # class Node
  84458. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84459. // by picking a polygon to split along. That polygon (and all other coplanar
  84460. // polygons) are added directly to that node and the other polygons are added to
  84461. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84462. // no distinction between internal and leaf nodes.
  84463. var Node = /** @class */ (function () {
  84464. function Node(polygons) {
  84465. this.plane = null;
  84466. this.front = null;
  84467. this.back = null;
  84468. this.polygons = new Array();
  84469. if (polygons) {
  84470. this.build(polygons);
  84471. }
  84472. }
  84473. Node.prototype.clone = function () {
  84474. var node = new Node();
  84475. node.plane = this.plane && this.plane.clone();
  84476. node.front = this.front && this.front.clone();
  84477. node.back = this.back && this.back.clone();
  84478. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84479. return node;
  84480. };
  84481. // Convert solid space to empty space and empty space to solid space.
  84482. Node.prototype.invert = function () {
  84483. for (var i = 0; i < this.polygons.length; i++) {
  84484. this.polygons[i].flip();
  84485. }
  84486. if (this.plane) {
  84487. this.plane.flip();
  84488. }
  84489. if (this.front) {
  84490. this.front.invert();
  84491. }
  84492. if (this.back) {
  84493. this.back.invert();
  84494. }
  84495. var temp = this.front;
  84496. this.front = this.back;
  84497. this.back = temp;
  84498. };
  84499. // Recursively remove all polygons in `polygons` that are inside this BSP
  84500. // tree.
  84501. Node.prototype.clipPolygons = function (polygons) {
  84502. if (!this.plane)
  84503. return polygons.slice();
  84504. var front = new Array(), back = new Array();
  84505. for (var i = 0; i < polygons.length; i++) {
  84506. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84507. }
  84508. if (this.front) {
  84509. front = this.front.clipPolygons(front);
  84510. }
  84511. if (this.back) {
  84512. back = this.back.clipPolygons(back);
  84513. }
  84514. else {
  84515. back = [];
  84516. }
  84517. return front.concat(back);
  84518. };
  84519. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84520. // `bsp`.
  84521. Node.prototype.clipTo = function (bsp) {
  84522. this.polygons = bsp.clipPolygons(this.polygons);
  84523. if (this.front)
  84524. this.front.clipTo(bsp);
  84525. if (this.back)
  84526. this.back.clipTo(bsp);
  84527. };
  84528. // Return a list of all polygons in this BSP tree.
  84529. Node.prototype.allPolygons = function () {
  84530. var polygons = this.polygons.slice();
  84531. if (this.front)
  84532. polygons = polygons.concat(this.front.allPolygons());
  84533. if (this.back)
  84534. polygons = polygons.concat(this.back.allPolygons());
  84535. return polygons;
  84536. };
  84537. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84538. // new polygons are filtered down to the bottom of the tree and become new
  84539. // nodes there. Each set of polygons is partitioned using the first polygon
  84540. // (no heuristic is used to pick a good split).
  84541. Node.prototype.build = function (polygons) {
  84542. if (!polygons.length)
  84543. return;
  84544. if (!this.plane)
  84545. this.plane = polygons[0].plane.clone();
  84546. var front = new Array(), back = new Array();
  84547. for (var i = 0; i < polygons.length; i++) {
  84548. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84549. }
  84550. if (front.length) {
  84551. if (!this.front)
  84552. this.front = new Node();
  84553. this.front.build(front);
  84554. }
  84555. if (back.length) {
  84556. if (!this.back)
  84557. this.back = new Node();
  84558. this.back.build(back);
  84559. }
  84560. };
  84561. return Node;
  84562. }());
  84563. var CSG = /** @class */ (function () {
  84564. function CSG() {
  84565. this.polygons = new Array();
  84566. }
  84567. // Convert BABYLON.Mesh to BABYLON.CSG
  84568. CSG.FromMesh = function (mesh) {
  84569. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84570. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84571. if (mesh instanceof BABYLON.Mesh) {
  84572. mesh.computeWorldMatrix(true);
  84573. matrix = mesh.getWorldMatrix();
  84574. meshPosition = mesh.position.clone();
  84575. meshRotation = mesh.rotation.clone();
  84576. if (mesh.rotationQuaternion) {
  84577. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84578. }
  84579. meshScaling = mesh.scaling.clone();
  84580. }
  84581. else {
  84582. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84583. }
  84584. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84585. var subMeshes = mesh.subMeshes;
  84586. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84587. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84588. vertices = [];
  84589. for (var j = 0; j < 3; j++) {
  84590. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84591. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84592. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84593. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84594. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84595. vertex = new Vertex(position, normal, uv);
  84596. vertices.push(vertex);
  84597. }
  84598. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84599. // To handle the case of degenerated triangle
  84600. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84601. if (polygon.plane)
  84602. polygons.push(polygon);
  84603. }
  84604. }
  84605. var csg = CSG.FromPolygons(polygons);
  84606. csg.matrix = matrix;
  84607. csg.position = meshPosition;
  84608. csg.rotation = meshRotation;
  84609. csg.scaling = meshScaling;
  84610. csg.rotationQuaternion = meshRotationQuaternion;
  84611. currentCSGMeshId++;
  84612. return csg;
  84613. };
  84614. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84615. CSG.FromPolygons = function (polygons) {
  84616. var csg = new CSG();
  84617. csg.polygons = polygons;
  84618. return csg;
  84619. };
  84620. CSG.prototype.clone = function () {
  84621. var csg = new CSG();
  84622. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84623. csg.copyTransformAttributes(this);
  84624. return csg;
  84625. };
  84626. CSG.prototype.union = function (csg) {
  84627. var a = new Node(this.clone().polygons);
  84628. var b = new Node(csg.clone().polygons);
  84629. a.clipTo(b);
  84630. b.clipTo(a);
  84631. b.invert();
  84632. b.clipTo(a);
  84633. b.invert();
  84634. a.build(b.allPolygons());
  84635. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84636. };
  84637. CSG.prototype.unionInPlace = function (csg) {
  84638. var a = new Node(this.polygons);
  84639. var b = new Node(csg.polygons);
  84640. a.clipTo(b);
  84641. b.clipTo(a);
  84642. b.invert();
  84643. b.clipTo(a);
  84644. b.invert();
  84645. a.build(b.allPolygons());
  84646. this.polygons = a.allPolygons();
  84647. };
  84648. CSG.prototype.subtract = function (csg) {
  84649. var a = new Node(this.clone().polygons);
  84650. var b = new Node(csg.clone().polygons);
  84651. a.invert();
  84652. a.clipTo(b);
  84653. b.clipTo(a);
  84654. b.invert();
  84655. b.clipTo(a);
  84656. b.invert();
  84657. a.build(b.allPolygons());
  84658. a.invert();
  84659. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84660. };
  84661. CSG.prototype.subtractInPlace = function (csg) {
  84662. var a = new Node(this.polygons);
  84663. var b = new Node(csg.polygons);
  84664. a.invert();
  84665. a.clipTo(b);
  84666. b.clipTo(a);
  84667. b.invert();
  84668. b.clipTo(a);
  84669. b.invert();
  84670. a.build(b.allPolygons());
  84671. a.invert();
  84672. this.polygons = a.allPolygons();
  84673. };
  84674. CSG.prototype.intersect = function (csg) {
  84675. var a = new Node(this.clone().polygons);
  84676. var b = new Node(csg.clone().polygons);
  84677. a.invert();
  84678. b.clipTo(a);
  84679. b.invert();
  84680. a.clipTo(b);
  84681. b.clipTo(a);
  84682. a.build(b.allPolygons());
  84683. a.invert();
  84684. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84685. };
  84686. CSG.prototype.intersectInPlace = function (csg) {
  84687. var a = new Node(this.polygons);
  84688. var b = new Node(csg.polygons);
  84689. a.invert();
  84690. b.clipTo(a);
  84691. b.invert();
  84692. a.clipTo(b);
  84693. b.clipTo(a);
  84694. a.build(b.allPolygons());
  84695. a.invert();
  84696. this.polygons = a.allPolygons();
  84697. };
  84698. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84699. // not modified.
  84700. CSG.prototype.inverse = function () {
  84701. var csg = this.clone();
  84702. csg.inverseInPlace();
  84703. return csg;
  84704. };
  84705. CSG.prototype.inverseInPlace = function () {
  84706. this.polygons.map(function (p) { p.flip(); });
  84707. };
  84708. // This is used to keep meshes transformations so they can be restored
  84709. // when we build back a Babylon Mesh
  84710. // NB : All CSG operations are performed in world coordinates
  84711. CSG.prototype.copyTransformAttributes = function (csg) {
  84712. this.matrix = csg.matrix;
  84713. this.position = csg.position;
  84714. this.rotation = csg.rotation;
  84715. this.scaling = csg.scaling;
  84716. this.rotationQuaternion = csg.rotationQuaternion;
  84717. return this;
  84718. };
  84719. // Build Raw mesh from CSG
  84720. // Coordinates here are in world space
  84721. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84722. var matrix = this.matrix.clone();
  84723. matrix.invert();
  84724. 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;
  84725. if (keepSubMeshes) {
  84726. // Sort Polygons, since subMeshes are indices range
  84727. polygons.sort(function (a, b) {
  84728. if (a.shared.meshId === b.shared.meshId) {
  84729. return a.shared.subMeshId - b.shared.subMeshId;
  84730. }
  84731. else {
  84732. return a.shared.meshId - b.shared.meshId;
  84733. }
  84734. });
  84735. }
  84736. for (var i = 0, il = polygons.length; i < il; i++) {
  84737. polygon = polygons[i];
  84738. // Building SubMeshes
  84739. if (!subMesh_dict[polygon.shared.meshId]) {
  84740. subMesh_dict[polygon.shared.meshId] = {};
  84741. }
  84742. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84743. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84744. indexStart: +Infinity,
  84745. indexEnd: -Infinity,
  84746. materialIndex: polygon.shared.materialIndex
  84747. };
  84748. }
  84749. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84750. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84751. polygonIndices[0] = 0;
  84752. polygonIndices[1] = j - 1;
  84753. polygonIndices[2] = j;
  84754. for (var k = 0; k < 3; k++) {
  84755. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84756. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84757. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84758. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84759. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84760. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84761. // Check if 2 points can be merged
  84762. if (!(typeof vertex_idx !== 'undefined' &&
  84763. normals[vertex_idx * 3] === localNormal.x &&
  84764. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84765. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84766. uvs[vertex_idx * 2] === uv.x &&
  84767. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84768. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84769. uvs.push(uv.x, uv.y);
  84770. normals.push(normal.x, normal.y, normal.z);
  84771. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84772. }
  84773. indices.push(vertex_idx);
  84774. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84775. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84776. currentIndex++;
  84777. }
  84778. }
  84779. }
  84780. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84781. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84782. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84783. mesh.setIndices(indices, null);
  84784. if (keepSubMeshes) {
  84785. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84786. var materialIndexOffset = 0, materialMaxIndex;
  84787. mesh.subMeshes = new Array();
  84788. for (var m in subMesh_dict) {
  84789. materialMaxIndex = -1;
  84790. for (var sm in subMesh_dict[m]) {
  84791. subMesh_obj = subMesh_dict[m][sm];
  84792. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84793. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84794. }
  84795. materialIndexOffset += ++materialMaxIndex;
  84796. }
  84797. }
  84798. return mesh;
  84799. };
  84800. // Build Mesh from CSG taking material and transforms into account
  84801. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84802. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84803. mesh.material = material;
  84804. mesh.position.copyFrom(this.position);
  84805. mesh.rotation.copyFrom(this.rotation);
  84806. if (this.rotationQuaternion) {
  84807. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84808. }
  84809. mesh.scaling.copyFrom(this.scaling);
  84810. mesh.computeWorldMatrix(true);
  84811. return mesh;
  84812. };
  84813. return CSG;
  84814. }());
  84815. BABYLON.CSG = CSG;
  84816. })(BABYLON || (BABYLON = {}));
  84817. //# sourceMappingURL=babylon.csg.js.map
  84818. var BABYLON;
  84819. (function (BABYLON) {
  84820. var LensFlare = /** @class */ (function () {
  84821. function LensFlare(size, position, color, imgUrl, system) {
  84822. this.size = size;
  84823. this.position = position;
  84824. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84825. this.color = color || new BABYLON.Color3(1, 1, 1);
  84826. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84827. this._system = system;
  84828. system.lensFlares.push(this);
  84829. }
  84830. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84831. return new LensFlare(size, position, color, imgUrl, system);
  84832. };
  84833. LensFlare.prototype.dispose = function () {
  84834. if (this.texture) {
  84835. this.texture.dispose();
  84836. }
  84837. // Remove from scene
  84838. var index = this._system.lensFlares.indexOf(this);
  84839. this._system.lensFlares.splice(index, 1);
  84840. };
  84841. ;
  84842. return LensFlare;
  84843. }());
  84844. BABYLON.LensFlare = LensFlare;
  84845. })(BABYLON || (BABYLON = {}));
  84846. //# sourceMappingURL=babylon.lensFlare.js.map
  84847. var BABYLON;
  84848. (function (BABYLON) {
  84849. // Adds the parser to the scene parsers.
  84850. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84851. // Lens flares
  84852. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84853. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84854. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84855. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84856. container.lensFlareSystems.push(lf);
  84857. }
  84858. }
  84859. });
  84860. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84861. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84862. if (this.lensFlareSystems[index].name === name) {
  84863. return this.lensFlareSystems[index];
  84864. }
  84865. }
  84866. return null;
  84867. };
  84868. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84869. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84870. if (this.lensFlareSystems[index].id === id) {
  84871. return this.lensFlareSystems[index];
  84872. }
  84873. }
  84874. return null;
  84875. };
  84876. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84877. var index = this.lensFlareSystems.indexOf(toRemove);
  84878. if (index !== -1) {
  84879. this.lensFlareSystems.splice(index, 1);
  84880. }
  84881. return index;
  84882. };
  84883. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84884. this.lensFlareSystems.push(newLensFlareSystem);
  84885. };
  84886. /**
  84887. * Defines the lens flare scene component responsible to manage any lens flares
  84888. * in a given scene.
  84889. */
  84890. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84891. /**
  84892. * Creates a new instance of the component for the given scene
  84893. * @param scene Defines the scene to register the component in
  84894. */
  84895. function LensFlareSystemSceneComponent(scene) {
  84896. /**
  84897. * The component name helpfull to identify the component in the list of scene components.
  84898. */
  84899. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84900. this.scene = scene;
  84901. scene.lensFlareSystems = new Array();
  84902. }
  84903. /**
  84904. * Registers the component in a given scene
  84905. */
  84906. LensFlareSystemSceneComponent.prototype.register = function () {
  84907. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84908. };
  84909. /**
  84910. * Rebuilds the elements related to this component in case of
  84911. * context lost for instance.
  84912. */
  84913. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84914. // Nothing to do for lens flare
  84915. };
  84916. /**
  84917. * Adds all the element from the container to the scene
  84918. * @param container the container holding the elements
  84919. */
  84920. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84921. var _this = this;
  84922. if (!container.lensFlareSystems) {
  84923. return;
  84924. }
  84925. container.lensFlareSystems.forEach(function (o) {
  84926. _this.scene.addLensFlareSystem(o);
  84927. });
  84928. };
  84929. /**
  84930. * Removes all the elements in the container from the scene
  84931. * @param container contains the elements to remove
  84932. */
  84933. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84934. var _this = this;
  84935. if (!container.lensFlareSystems) {
  84936. return;
  84937. }
  84938. container.lensFlareSystems.forEach(function (o) {
  84939. _this.scene.removeLensFlareSystem(o);
  84940. });
  84941. };
  84942. /**
  84943. * Serializes the component data to the specified json object
  84944. * @param serializationObject The object to serialize to
  84945. */
  84946. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84947. // Lens flares
  84948. serializationObject.lensFlareSystems = [];
  84949. var lensFlareSystems = this.scene.lensFlareSystems;
  84950. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84951. var lensFlareSystem = lensFlareSystems_1[_i];
  84952. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84953. }
  84954. };
  84955. /**
  84956. * Disposes the component and the associated ressources.
  84957. */
  84958. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84959. var lensFlareSystems = this.scene.lensFlareSystems;
  84960. while (lensFlareSystems.length) {
  84961. lensFlareSystems[0].dispose();
  84962. }
  84963. };
  84964. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84965. // Lens flares
  84966. if (this.scene.lensFlaresEnabled) {
  84967. var lensFlareSystems = this.scene.lensFlareSystems;
  84968. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84969. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84970. var lensFlareSystem = lensFlareSystems_2[_i];
  84971. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84972. lensFlareSystem.render();
  84973. }
  84974. }
  84975. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84976. }
  84977. };
  84978. return LensFlareSystemSceneComponent;
  84979. }());
  84980. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84981. })(BABYLON || (BABYLON = {}));
  84982. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84983. var BABYLON;
  84984. (function (BABYLON) {
  84985. var LensFlareSystem = /** @class */ (function () {
  84986. function LensFlareSystem(name, emitter, scene) {
  84987. this.name = name;
  84988. this.lensFlares = new Array();
  84989. this.borderLimit = 300;
  84990. this.viewportBorder = 0;
  84991. this.layerMask = 0x0FFFFFFF;
  84992. this._vertexBuffers = {};
  84993. this._isEnabled = true;
  84994. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84995. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84996. if (!component) {
  84997. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84998. scene._addComponent(component);
  84999. }
  85000. this._emitter = emitter;
  85001. this.id = name;
  85002. scene.lensFlareSystems.push(this);
  85003. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  85004. var engine = scene.getEngine();
  85005. // VBO
  85006. var vertices = [];
  85007. vertices.push(1, 1);
  85008. vertices.push(-1, 1);
  85009. vertices.push(-1, -1);
  85010. vertices.push(1, -1);
  85011. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85012. // Indices
  85013. var indices = [];
  85014. indices.push(0);
  85015. indices.push(1);
  85016. indices.push(2);
  85017. indices.push(0);
  85018. indices.push(2);
  85019. indices.push(3);
  85020. this._indexBuffer = engine.createIndexBuffer(indices);
  85021. // Effects
  85022. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  85023. }
  85024. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  85025. get: function () {
  85026. return this._isEnabled;
  85027. },
  85028. set: function (value) {
  85029. this._isEnabled = value;
  85030. },
  85031. enumerable: true,
  85032. configurable: true
  85033. });
  85034. LensFlareSystem.prototype.getScene = function () {
  85035. return this._scene;
  85036. };
  85037. LensFlareSystem.prototype.getEmitter = function () {
  85038. return this._emitter;
  85039. };
  85040. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  85041. this._emitter = newEmitter;
  85042. };
  85043. LensFlareSystem.prototype.getEmitterPosition = function () {
  85044. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  85045. };
  85046. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  85047. var position = this.getEmitterPosition();
  85048. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  85049. this._positionX = position.x;
  85050. this._positionY = position.y;
  85051. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  85052. if (this.viewportBorder > 0) {
  85053. globalViewport.x -= this.viewportBorder;
  85054. globalViewport.y -= this.viewportBorder;
  85055. globalViewport.width += this.viewportBorder * 2;
  85056. globalViewport.height += this.viewportBorder * 2;
  85057. position.x += this.viewportBorder;
  85058. position.y += this.viewportBorder;
  85059. this._positionX += this.viewportBorder;
  85060. this._positionY += this.viewportBorder;
  85061. }
  85062. if (position.z > 0) {
  85063. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  85064. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  85065. return true;
  85066. }
  85067. return true;
  85068. }
  85069. return false;
  85070. };
  85071. LensFlareSystem.prototype._isVisible = function () {
  85072. if (!this._isEnabled || !this._scene.activeCamera) {
  85073. return false;
  85074. }
  85075. var emitterPosition = this.getEmitterPosition();
  85076. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  85077. var distance = direction.length();
  85078. direction.normalize();
  85079. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  85080. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  85081. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  85082. };
  85083. LensFlareSystem.prototype.render = function () {
  85084. if (!this._effect.isReady() || !this._scene.activeCamera)
  85085. return false;
  85086. var engine = this._scene.getEngine();
  85087. var viewport = this._scene.activeCamera.viewport;
  85088. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  85089. // Position
  85090. if (!this.computeEffectivePosition(globalViewport)) {
  85091. return false;
  85092. }
  85093. // Visibility
  85094. if (!this._isVisible()) {
  85095. return false;
  85096. }
  85097. // Intensity
  85098. var awayX;
  85099. var awayY;
  85100. if (this._positionX < this.borderLimit + globalViewport.x) {
  85101. awayX = this.borderLimit + globalViewport.x - this._positionX;
  85102. }
  85103. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  85104. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  85105. }
  85106. else {
  85107. awayX = 0;
  85108. }
  85109. if (this._positionY < this.borderLimit + globalViewport.y) {
  85110. awayY = this.borderLimit + globalViewport.y - this._positionY;
  85111. }
  85112. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  85113. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  85114. }
  85115. else {
  85116. awayY = 0;
  85117. }
  85118. var away = (awayX > awayY) ? awayX : awayY;
  85119. away -= this.viewportBorder;
  85120. if (away > this.borderLimit) {
  85121. away = this.borderLimit;
  85122. }
  85123. var intensity = 1.0 - (away / this.borderLimit);
  85124. if (intensity < 0) {
  85125. return false;
  85126. }
  85127. if (intensity > 1.0) {
  85128. intensity = 1.0;
  85129. }
  85130. if (this.viewportBorder > 0) {
  85131. globalViewport.x += this.viewportBorder;
  85132. globalViewport.y += this.viewportBorder;
  85133. globalViewport.width -= this.viewportBorder * 2;
  85134. globalViewport.height -= this.viewportBorder * 2;
  85135. this._positionX -= this.viewportBorder;
  85136. this._positionY -= this.viewportBorder;
  85137. }
  85138. // Position
  85139. var centerX = globalViewport.x + globalViewport.width / 2;
  85140. var centerY = globalViewport.y + globalViewport.height / 2;
  85141. var distX = centerX - this._positionX;
  85142. var distY = centerY - this._positionY;
  85143. // Effects
  85144. engine.enableEffect(this._effect);
  85145. engine.setState(false);
  85146. engine.setDepthBuffer(false);
  85147. // VBOs
  85148. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  85149. // Flares
  85150. for (var index = 0; index < this.lensFlares.length; index++) {
  85151. var flare = this.lensFlares[index];
  85152. engine.setAlphaMode(flare.alphaMode);
  85153. var x = centerX - (distX * flare.position);
  85154. var y = centerY - (distY * flare.position);
  85155. var cw = flare.size;
  85156. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  85157. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  85158. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  85159. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  85160. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  85161. // Texture
  85162. this._effect.setTexture("textureSampler", flare.texture);
  85163. // Color
  85164. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  85165. // Draw order
  85166. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85167. }
  85168. engine.setDepthBuffer(true);
  85169. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85170. return true;
  85171. };
  85172. LensFlareSystem.prototype.dispose = function () {
  85173. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85174. if (vertexBuffer) {
  85175. vertexBuffer.dispose();
  85176. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85177. }
  85178. if (this._indexBuffer) {
  85179. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85180. this._indexBuffer = null;
  85181. }
  85182. while (this.lensFlares.length) {
  85183. this.lensFlares[0].dispose();
  85184. }
  85185. // Remove from scene
  85186. var index = this._scene.lensFlareSystems.indexOf(this);
  85187. this._scene.lensFlareSystems.splice(index, 1);
  85188. };
  85189. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  85190. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  85191. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  85192. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  85193. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  85194. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  85195. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  85196. var parsedFlare = parsedLensFlareSystem.flares[index];
  85197. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  85198. }
  85199. return lensFlareSystem;
  85200. };
  85201. LensFlareSystem.prototype.serialize = function () {
  85202. var serializationObject = {};
  85203. serializationObject.id = this.id;
  85204. serializationObject.name = this.name;
  85205. serializationObject.emitterId = this.getEmitter().id;
  85206. serializationObject.borderLimit = this.borderLimit;
  85207. serializationObject.flares = [];
  85208. for (var index = 0; index < this.lensFlares.length; index++) {
  85209. var flare = this.lensFlares[index];
  85210. serializationObject.flares.push({
  85211. size: flare.size,
  85212. position: flare.position,
  85213. color: flare.color.asArray(),
  85214. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  85215. });
  85216. }
  85217. return serializationObject;
  85218. };
  85219. return LensFlareSystem;
  85220. }());
  85221. BABYLON.LensFlareSystem = LensFlareSystem;
  85222. })(BABYLON || (BABYLON = {}));
  85223. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  85224. var BABYLON;
  85225. (function (BABYLON) {
  85226. /**
  85227. * This is a holder class for the physics joint created by the physics plugin.
  85228. * It holds a set of functions to control the underlying joint.
  85229. */
  85230. var PhysicsJoint = /** @class */ (function () {
  85231. function PhysicsJoint(type, jointData) {
  85232. this.type = type;
  85233. this.jointData = jointData;
  85234. jointData.nativeParams = jointData.nativeParams || {};
  85235. }
  85236. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  85237. get: function () {
  85238. return this._physicsJoint;
  85239. },
  85240. set: function (newJoint) {
  85241. if (this._physicsJoint) {
  85242. //remove from the wolrd
  85243. }
  85244. this._physicsJoint = newJoint;
  85245. },
  85246. enumerable: true,
  85247. configurable: true
  85248. });
  85249. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  85250. set: function (physicsPlugin) {
  85251. this._physicsPlugin = physicsPlugin;
  85252. },
  85253. enumerable: true,
  85254. configurable: true
  85255. });
  85256. /**
  85257. * Execute a function that is physics-plugin specific.
  85258. * @param {Function} func the function that will be executed.
  85259. * It accepts two parameters: the physics world and the physics joint.
  85260. */
  85261. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  85262. func(this._physicsPlugin.world, this._physicsJoint);
  85263. };
  85264. //TODO check if the native joints are the same
  85265. //Joint Types
  85266. PhysicsJoint.DistanceJoint = 0;
  85267. PhysicsJoint.HingeJoint = 1;
  85268. PhysicsJoint.BallAndSocketJoint = 2;
  85269. PhysicsJoint.WheelJoint = 3;
  85270. PhysicsJoint.SliderJoint = 4;
  85271. //OIMO
  85272. PhysicsJoint.PrismaticJoint = 5;
  85273. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  85274. PhysicsJoint.UniversalJoint = 6;
  85275. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  85276. //Cannon
  85277. //Similar to a Ball-Joint. Different in params
  85278. PhysicsJoint.PointToPointJoint = 8;
  85279. //Cannon only at the moment
  85280. PhysicsJoint.SpringJoint = 9;
  85281. PhysicsJoint.LockJoint = 10;
  85282. return PhysicsJoint;
  85283. }());
  85284. BABYLON.PhysicsJoint = PhysicsJoint;
  85285. /**
  85286. * A class representing a physics distance joint.
  85287. */
  85288. var DistanceJoint = /** @class */ (function (_super) {
  85289. __extends(DistanceJoint, _super);
  85290. function DistanceJoint(jointData) {
  85291. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  85292. }
  85293. /**
  85294. * Update the predefined distance.
  85295. */
  85296. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  85297. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  85298. };
  85299. return DistanceJoint;
  85300. }(PhysicsJoint));
  85301. BABYLON.DistanceJoint = DistanceJoint;
  85302. var MotorEnabledJoint = /** @class */ (function (_super) {
  85303. __extends(MotorEnabledJoint, _super);
  85304. function MotorEnabledJoint(type, jointData) {
  85305. return _super.call(this, type, jointData) || this;
  85306. }
  85307. /**
  85308. * Set the motor values.
  85309. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85310. * @param {number} force the force to apply
  85311. * @param {number} maxForce max force for this motor.
  85312. */
  85313. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  85314. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85315. };
  85316. /**
  85317. * Set the motor's limits.
  85318. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85319. */
  85320. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85321. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85322. };
  85323. return MotorEnabledJoint;
  85324. }(PhysicsJoint));
  85325. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  85326. /**
  85327. * This class represents a single hinge physics joint
  85328. */
  85329. var HingeJoint = /** @class */ (function (_super) {
  85330. __extends(HingeJoint, _super);
  85331. function HingeJoint(jointData) {
  85332. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  85333. }
  85334. /**
  85335. * Set the motor values.
  85336. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85337. * @param {number} force the force to apply
  85338. * @param {number} maxForce max force for this motor.
  85339. */
  85340. HingeJoint.prototype.setMotor = function (force, maxForce) {
  85341. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85342. };
  85343. /**
  85344. * Set the motor's limits.
  85345. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85346. */
  85347. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85348. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85349. };
  85350. return HingeJoint;
  85351. }(MotorEnabledJoint));
  85352. BABYLON.HingeJoint = HingeJoint;
  85353. /**
  85354. * This class represents a dual hinge physics joint (same as wheel joint)
  85355. */
  85356. var Hinge2Joint = /** @class */ (function (_super) {
  85357. __extends(Hinge2Joint, _super);
  85358. function Hinge2Joint(jointData) {
  85359. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  85360. }
  85361. /**
  85362. * Set the motor values.
  85363. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85364. * @param {number} force the force to apply
  85365. * @param {number} maxForce max force for this motor.
  85366. * @param {motorIndex} the motor's index, 0 or 1.
  85367. */
  85368. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  85369. if (motorIndex === void 0) { motorIndex = 0; }
  85370. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  85371. };
  85372. /**
  85373. * Set the motor limits.
  85374. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85375. * @param {number} upperLimit the upper limit
  85376. * @param {number} lowerLimit lower limit
  85377. * @param {motorIndex} the motor's index, 0 or 1.
  85378. */
  85379. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  85380. if (motorIndex === void 0) { motorIndex = 0; }
  85381. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  85382. };
  85383. return Hinge2Joint;
  85384. }(MotorEnabledJoint));
  85385. BABYLON.Hinge2Joint = Hinge2Joint;
  85386. })(BABYLON || (BABYLON = {}));
  85387. //# sourceMappingURL=babylon.physicsJoint.js.map
  85388. var BABYLON;
  85389. (function (BABYLON) {
  85390. var PhysicsImpostor = /** @class */ (function () {
  85391. function PhysicsImpostor(object, type, _options, _scene) {
  85392. if (_options === void 0) { _options = { mass: 0 }; }
  85393. var _this = this;
  85394. this.object = object;
  85395. this.type = type;
  85396. this._options = _options;
  85397. this._scene = _scene;
  85398. this._bodyUpdateRequired = false;
  85399. this._onBeforePhysicsStepCallbacks = new Array();
  85400. this._onAfterPhysicsStepCallbacks = new Array();
  85401. this._onPhysicsCollideCallbacks = [];
  85402. this._deltaPosition = BABYLON.Vector3.Zero();
  85403. this._isDisposed = false;
  85404. //temp variables for parent rotation calculations
  85405. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  85406. this._tmpQuat = new BABYLON.Quaternion();
  85407. this._tmpQuat2 = new BABYLON.Quaternion();
  85408. /**
  85409. * this function is executed by the physics engine.
  85410. */
  85411. this.beforeStep = function () {
  85412. if (!_this._physicsEngine) {
  85413. return;
  85414. }
  85415. _this.object.translate(_this._deltaPosition, -1);
  85416. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  85417. _this.object.computeWorldMatrix(false);
  85418. if (_this.object.parent && _this.object.rotationQuaternion) {
  85419. _this.getParentsRotation();
  85420. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  85421. }
  85422. else {
  85423. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  85424. }
  85425. if (!_this._options.disableBidirectionalTransformation) {
  85426. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  85427. }
  85428. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  85429. func(_this);
  85430. });
  85431. };
  85432. /**
  85433. * this function is executed by the physics engine.
  85434. */
  85435. this.afterStep = function () {
  85436. if (!_this._physicsEngine) {
  85437. return;
  85438. }
  85439. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  85440. func(_this);
  85441. });
  85442. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85443. // object has now its world rotation. needs to be converted to local.
  85444. if (_this.object.parent && _this.object.rotationQuaternion) {
  85445. _this.getParentsRotation();
  85446. _this._tmpQuat.conjugateInPlace();
  85447. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85448. }
  85449. // take the position set and make it the absolute position of this object.
  85450. _this.object.setAbsolutePosition(_this.object.position);
  85451. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85452. _this.object.translate(_this._deltaPosition, 1);
  85453. };
  85454. /**
  85455. * Legacy collision detection event support
  85456. */
  85457. this.onCollideEvent = null;
  85458. //event and body object due to cannon's event-based architecture.
  85459. this.onCollide = function (e) {
  85460. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85461. return;
  85462. }
  85463. if (!_this._physicsEngine) {
  85464. return;
  85465. }
  85466. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85467. if (otherImpostor) {
  85468. // Legacy collision detection event support
  85469. if (_this.onCollideEvent) {
  85470. _this.onCollideEvent(_this, otherImpostor);
  85471. }
  85472. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85473. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85474. }).forEach(function (obj) {
  85475. obj.callback(_this, otherImpostor);
  85476. });
  85477. }
  85478. };
  85479. //sanity check!
  85480. if (!this.object) {
  85481. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85482. return;
  85483. }
  85484. //legacy support for old syntax.
  85485. if (!this._scene && object.getScene) {
  85486. this._scene = object.getScene();
  85487. }
  85488. if (!this._scene) {
  85489. return;
  85490. }
  85491. this._physicsEngine = this._scene.getPhysicsEngine();
  85492. if (!this._physicsEngine) {
  85493. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85494. }
  85495. else {
  85496. //set the object's quaternion, if not set
  85497. if (!this.object.rotationQuaternion) {
  85498. if (this.object.rotation) {
  85499. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85500. }
  85501. else {
  85502. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85503. }
  85504. }
  85505. //default options params
  85506. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85507. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85508. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85509. this._joints = [];
  85510. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85511. if (!this.object.parent || this._options.ignoreParent) {
  85512. this._init();
  85513. }
  85514. else if (this.object.parent.physicsImpostor) {
  85515. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85516. }
  85517. }
  85518. }
  85519. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85520. get: function () {
  85521. return this._isDisposed;
  85522. },
  85523. enumerable: true,
  85524. configurable: true
  85525. });
  85526. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85527. get: function () {
  85528. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85529. },
  85530. set: function (value) {
  85531. this.setMass(value);
  85532. },
  85533. enumerable: true,
  85534. configurable: true
  85535. });
  85536. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85537. get: function () {
  85538. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85539. },
  85540. set: function (value) {
  85541. if (!this._physicsEngine) {
  85542. return;
  85543. }
  85544. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85545. },
  85546. enumerable: true,
  85547. configurable: true
  85548. });
  85549. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85550. get: function () {
  85551. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85552. },
  85553. set: function (value) {
  85554. if (!this._physicsEngine) {
  85555. return;
  85556. }
  85557. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85558. },
  85559. enumerable: true,
  85560. configurable: true
  85561. });
  85562. /**
  85563. * This function will completly initialize this impostor.
  85564. * It will create a new body - but only if this mesh has no parent.
  85565. * If it has, this impostor will not be used other than to define the impostor
  85566. * of the child mesh.
  85567. */
  85568. PhysicsImpostor.prototype._init = function () {
  85569. if (!this._physicsEngine) {
  85570. return;
  85571. }
  85572. this._physicsEngine.removeImpostor(this);
  85573. this.physicsBody = null;
  85574. this._parent = this._parent || this._getPhysicsParent();
  85575. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85576. this._physicsEngine.addImpostor(this);
  85577. }
  85578. };
  85579. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85580. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85581. var parentMesh = this.object.parent;
  85582. return parentMesh.physicsImpostor;
  85583. }
  85584. return null;
  85585. };
  85586. /**
  85587. * Should a new body be generated.
  85588. */
  85589. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85590. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85591. };
  85592. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85593. this.forceUpdate();
  85594. };
  85595. /**
  85596. * Force a regeneration of this or the parent's impostor's body.
  85597. * Use under cautious - This will remove all joints already implemented.
  85598. */
  85599. PhysicsImpostor.prototype.forceUpdate = function () {
  85600. this._init();
  85601. if (this.parent && !this._options.ignoreParent) {
  85602. this.parent.forceUpdate();
  85603. }
  85604. };
  85605. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85606. /*public get mesh(): AbstractMesh {
  85607. return this._mesh;
  85608. }*/
  85609. /**
  85610. * Gets the body that holds this impostor. Either its own, or its parent.
  85611. */
  85612. get: function () {
  85613. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85614. },
  85615. /**
  85616. * Set the physics body. Used mainly by the physics engine/plugin
  85617. */
  85618. set: function (physicsBody) {
  85619. if (this._physicsBody && this._physicsEngine) {
  85620. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85621. }
  85622. this._physicsBody = physicsBody;
  85623. this.resetUpdateFlags();
  85624. },
  85625. enumerable: true,
  85626. configurable: true
  85627. });
  85628. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85629. get: function () {
  85630. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85631. },
  85632. set: function (value) {
  85633. this._parent = value;
  85634. },
  85635. enumerable: true,
  85636. configurable: true
  85637. });
  85638. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85639. this._bodyUpdateRequired = false;
  85640. };
  85641. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85642. if (this.object.getBoundingInfo) {
  85643. var q = this.object.rotationQuaternion;
  85644. //reset rotation
  85645. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85646. //calculate the world matrix with no rotation
  85647. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85648. var boundingInfo = this.object.getBoundingInfo();
  85649. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85650. //bring back the rotation
  85651. this.object.rotationQuaternion = q;
  85652. //calculate the world matrix with the new rotation
  85653. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85654. return size;
  85655. }
  85656. else {
  85657. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85658. }
  85659. };
  85660. PhysicsImpostor.prototype.getObjectCenter = function () {
  85661. if (this.object.getBoundingInfo) {
  85662. var boundingInfo = this.object.getBoundingInfo();
  85663. return boundingInfo.boundingBox.centerWorld;
  85664. }
  85665. else {
  85666. return this.object.position;
  85667. }
  85668. };
  85669. /**
  85670. * Get a specific parametes from the options parameter.
  85671. */
  85672. PhysicsImpostor.prototype.getParam = function (paramName) {
  85673. return this._options[paramName];
  85674. };
  85675. /**
  85676. * Sets a specific parameter in the options given to the physics plugin
  85677. */
  85678. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85679. this._options[paramName] = value;
  85680. this._bodyUpdateRequired = true;
  85681. };
  85682. /**
  85683. * Specifically change the body's mass option. Won't recreate the physics body object
  85684. */
  85685. PhysicsImpostor.prototype.setMass = function (mass) {
  85686. if (this.getParam("mass") !== mass) {
  85687. this.setParam("mass", mass);
  85688. }
  85689. if (this._physicsEngine) {
  85690. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85691. }
  85692. };
  85693. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85694. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85695. };
  85696. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85697. if (this._physicsEngine) {
  85698. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85699. }
  85700. };
  85701. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85702. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85703. };
  85704. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85705. if (this._physicsEngine) {
  85706. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85707. }
  85708. };
  85709. /**
  85710. * Execute a function with the physics plugin native code.
  85711. * Provide a function the will have two variables - the world object and the physics body object.
  85712. */
  85713. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85714. if (this._physicsEngine) {
  85715. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85716. }
  85717. };
  85718. /**
  85719. * Register a function that will be executed before the physics world is stepping forward.
  85720. */
  85721. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85722. this._onBeforePhysicsStepCallbacks.push(func);
  85723. };
  85724. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85725. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85726. if (index > -1) {
  85727. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85728. }
  85729. else {
  85730. BABYLON.Tools.Warn("Function to remove was not found");
  85731. }
  85732. };
  85733. /**
  85734. * Register a function that will be executed after the physics step
  85735. */
  85736. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85737. this._onAfterPhysicsStepCallbacks.push(func);
  85738. };
  85739. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85740. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85741. if (index > -1) {
  85742. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85743. }
  85744. else {
  85745. BABYLON.Tools.Warn("Function to remove was not found");
  85746. }
  85747. };
  85748. /**
  85749. * register a function that will be executed when this impostor collides against a different body.
  85750. */
  85751. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85752. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85753. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85754. };
  85755. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85756. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85757. var index = -1;
  85758. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85759. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85760. // chcek the arrays match
  85761. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85762. return collidedAgainstList.indexOf(impostor) > -1;
  85763. });
  85764. if (sameList) {
  85765. index = idx;
  85766. }
  85767. return sameList;
  85768. }
  85769. return false;
  85770. });
  85771. if (found) {
  85772. this._onPhysicsCollideCallbacks.splice(index, 1);
  85773. }
  85774. else {
  85775. BABYLON.Tools.Warn("Function to remove was not found");
  85776. }
  85777. };
  85778. PhysicsImpostor.prototype.getParentsRotation = function () {
  85779. var parent = this.object.parent;
  85780. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85781. while (parent) {
  85782. if (parent.rotationQuaternion) {
  85783. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85784. }
  85785. else {
  85786. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85787. }
  85788. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85789. parent = parent.parent;
  85790. }
  85791. return this._tmpQuat;
  85792. };
  85793. /**
  85794. * Apply a force
  85795. */
  85796. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85797. if (this._physicsEngine) {
  85798. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85799. }
  85800. return this;
  85801. };
  85802. /**
  85803. * Apply an impulse
  85804. */
  85805. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85806. if (this._physicsEngine) {
  85807. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85808. }
  85809. return this;
  85810. };
  85811. /**
  85812. * A help function to create a joint.
  85813. */
  85814. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85815. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85816. this.addJoint(otherImpostor, joint);
  85817. return this;
  85818. };
  85819. /**
  85820. * Add a joint to this impostor with a different impostor.
  85821. */
  85822. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85823. this._joints.push({
  85824. otherImpostor: otherImpostor,
  85825. joint: joint
  85826. });
  85827. if (this._physicsEngine) {
  85828. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85829. }
  85830. return this;
  85831. };
  85832. /**
  85833. * Will keep this body still, in a sleep mode.
  85834. */
  85835. PhysicsImpostor.prototype.sleep = function () {
  85836. if (this._physicsEngine) {
  85837. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85838. }
  85839. return this;
  85840. };
  85841. /**
  85842. * Wake the body up.
  85843. */
  85844. PhysicsImpostor.prototype.wakeUp = function () {
  85845. if (this._physicsEngine) {
  85846. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85847. }
  85848. return this;
  85849. };
  85850. PhysicsImpostor.prototype.clone = function (newObject) {
  85851. if (!newObject)
  85852. return null;
  85853. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85854. };
  85855. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85856. var _this = this;
  85857. //no dispose if no physics engine is available.
  85858. if (!this._physicsEngine) {
  85859. return;
  85860. }
  85861. this._joints.forEach(function (j) {
  85862. if (_this._physicsEngine) {
  85863. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85864. }
  85865. });
  85866. //dispose the physics body
  85867. this._physicsEngine.removeImpostor(this);
  85868. if (this.parent) {
  85869. this.parent.forceUpdate();
  85870. }
  85871. else {
  85872. /*this._object.getChildMeshes().forEach(function(mesh) {
  85873. if (mesh.physicsImpostor) {
  85874. if (disposeChildren) {
  85875. mesh.physicsImpostor.dispose();
  85876. mesh.physicsImpostor = null;
  85877. }
  85878. }
  85879. })*/
  85880. }
  85881. this._isDisposed = true;
  85882. };
  85883. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85884. this._deltaPosition.copyFrom(position);
  85885. };
  85886. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85887. if (!this._deltaRotation) {
  85888. this._deltaRotation = new BABYLON.Quaternion();
  85889. }
  85890. this._deltaRotation.copyFrom(rotation);
  85891. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85892. };
  85893. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85894. if (this._physicsEngine) {
  85895. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85896. }
  85897. return this;
  85898. };
  85899. PhysicsImpostor.prototype.getRadius = function () {
  85900. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85901. };
  85902. /**
  85903. * Sync a bone with this impostor
  85904. * @param bone The bone to sync to the impostor.
  85905. * @param boneMesh The mesh that the bone is influencing.
  85906. * @param jointPivot The pivot of the joint / bone in local space.
  85907. * @param distToJoint Optional distance from the impostor to the joint.
  85908. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85909. */
  85910. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85911. var tempVec = PhysicsImpostor._tmpVecs[0];
  85912. var mesh = this.object;
  85913. if (mesh.rotationQuaternion) {
  85914. if (adjustRotation) {
  85915. var tempQuat = PhysicsImpostor._tmpQuat;
  85916. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85917. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85918. }
  85919. else {
  85920. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85921. }
  85922. }
  85923. tempVec.x = 0;
  85924. tempVec.y = 0;
  85925. tempVec.z = 0;
  85926. if (jointPivot) {
  85927. tempVec.x = jointPivot.x;
  85928. tempVec.y = jointPivot.y;
  85929. tempVec.z = jointPivot.z;
  85930. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85931. if (distToJoint === undefined || distToJoint === null) {
  85932. distToJoint = jointPivot.length();
  85933. }
  85934. tempVec.x *= distToJoint;
  85935. tempVec.y *= distToJoint;
  85936. tempVec.z *= distToJoint;
  85937. }
  85938. if (bone.getParent()) {
  85939. tempVec.addInPlace(mesh.getAbsolutePosition());
  85940. bone.setAbsolutePosition(tempVec, boneMesh);
  85941. }
  85942. else {
  85943. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85944. boneMesh.position.x -= tempVec.x;
  85945. boneMesh.position.y -= tempVec.y;
  85946. boneMesh.position.z -= tempVec.z;
  85947. }
  85948. };
  85949. /**
  85950. * Sync impostor to a bone
  85951. * @param bone The bone that the impostor will be synced to.
  85952. * @param boneMesh The mesh that the bone is influencing.
  85953. * @param jointPivot The pivot of the joint / bone in local space.
  85954. * @param distToJoint Optional distance from the impostor to the joint.
  85955. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85956. * @param boneAxis Optional vector3 axis the bone is aligned with
  85957. */
  85958. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85959. var mesh = this.object;
  85960. if (mesh.rotationQuaternion) {
  85961. if (adjustRotation) {
  85962. var tempQuat = PhysicsImpostor._tmpQuat;
  85963. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85964. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85965. }
  85966. else {
  85967. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85968. }
  85969. }
  85970. var pos = PhysicsImpostor._tmpVecs[0];
  85971. var boneDir = PhysicsImpostor._tmpVecs[1];
  85972. if (!boneAxis) {
  85973. boneAxis = PhysicsImpostor._tmpVecs[2];
  85974. boneAxis.x = 0;
  85975. boneAxis.y = 1;
  85976. boneAxis.z = 0;
  85977. }
  85978. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85979. bone.getAbsolutePositionToRef(boneMesh, pos);
  85980. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85981. distToJoint = jointPivot.length();
  85982. }
  85983. if (distToJoint !== undefined && distToJoint !== null) {
  85984. pos.x += boneDir.x * distToJoint;
  85985. pos.y += boneDir.y * distToJoint;
  85986. pos.z += boneDir.z * distToJoint;
  85987. }
  85988. mesh.setAbsolutePosition(pos);
  85989. };
  85990. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85991. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85992. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85993. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85994. //Impostor types
  85995. PhysicsImpostor.NoImpostor = 0;
  85996. PhysicsImpostor.SphereImpostor = 1;
  85997. PhysicsImpostor.BoxImpostor = 2;
  85998. PhysicsImpostor.PlaneImpostor = 3;
  85999. PhysicsImpostor.MeshImpostor = 4;
  86000. PhysicsImpostor.CylinderImpostor = 7;
  86001. PhysicsImpostor.ParticleImpostor = 8;
  86002. PhysicsImpostor.HeightmapImpostor = 9;
  86003. return PhysicsImpostor;
  86004. }());
  86005. BABYLON.PhysicsImpostor = PhysicsImpostor;
  86006. })(BABYLON || (BABYLON = {}));
  86007. //# sourceMappingURL=babylon.physicsImpostor.js.map
  86008. var BABYLON;
  86009. (function (BABYLON) {
  86010. var PhysicsEngine = /** @class */ (function () {
  86011. function PhysicsEngine(gravity, _physicsPlugin) {
  86012. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  86013. this._physicsPlugin = _physicsPlugin;
  86014. //new methods and parameters
  86015. this._impostors = [];
  86016. this._joints = [];
  86017. if (!this._physicsPlugin.isSupported()) {
  86018. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  86019. + "Please make sure it is included.");
  86020. }
  86021. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  86022. this.setGravity(gravity);
  86023. this.setTimeStep();
  86024. }
  86025. PhysicsEngine.prototype.setGravity = function (gravity) {
  86026. this.gravity = gravity;
  86027. this._physicsPlugin.setGravity(this.gravity);
  86028. };
  86029. /**
  86030. * Set the time step of the physics engine.
  86031. * default is 1/60.
  86032. * To slow it down, enter 1/600 for example.
  86033. * To speed it up, 1/30
  86034. * @param {number} newTimeStep the new timestep to apply to this world.
  86035. */
  86036. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  86037. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  86038. this._physicsPlugin.setTimeStep(newTimeStep);
  86039. };
  86040. /**
  86041. * Get the time step of the physics engine.
  86042. */
  86043. PhysicsEngine.prototype.getTimeStep = function () {
  86044. return this._physicsPlugin.getTimeStep();
  86045. };
  86046. PhysicsEngine.prototype.dispose = function () {
  86047. this._impostors.forEach(function (impostor) {
  86048. impostor.dispose();
  86049. });
  86050. this._physicsPlugin.dispose();
  86051. };
  86052. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  86053. return this._physicsPlugin.name;
  86054. };
  86055. /**
  86056. * Adding a new impostor for the impostor tracking.
  86057. * This will be done by the impostor itself.
  86058. * @param {PhysicsImpostor} impostor the impostor to add
  86059. */
  86060. PhysicsEngine.prototype.addImpostor = function (impostor) {
  86061. impostor.uniqueId = this._impostors.push(impostor);
  86062. //if no parent, generate the body
  86063. if (!impostor.parent) {
  86064. this._physicsPlugin.generatePhysicsBody(impostor);
  86065. }
  86066. };
  86067. /**
  86068. * Remove an impostor from the engine.
  86069. * This impostor and its mesh will not longer be updated by the physics engine.
  86070. * @param {PhysicsImpostor} impostor the impostor to remove
  86071. */
  86072. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  86073. var index = this._impostors.indexOf(impostor);
  86074. if (index > -1) {
  86075. var removed = this._impostors.splice(index, 1);
  86076. //Is it needed?
  86077. if (removed.length) {
  86078. //this will also remove it from the world.
  86079. removed[0].physicsBody = null;
  86080. }
  86081. }
  86082. };
  86083. /**
  86084. * Add a joint to the physics engine
  86085. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  86086. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  86087. * @param {PhysicsJoint} the joint that will connect both impostors.
  86088. */
  86089. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  86090. var impostorJoint = {
  86091. mainImpostor: mainImpostor,
  86092. connectedImpostor: connectedImpostor,
  86093. joint: joint
  86094. };
  86095. joint.physicsPlugin = this._physicsPlugin;
  86096. this._joints.push(impostorJoint);
  86097. this._physicsPlugin.generateJoint(impostorJoint);
  86098. };
  86099. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  86100. var matchingJoints = this._joints.filter(function (impostorJoint) {
  86101. return (impostorJoint.connectedImpostor === connectedImpostor
  86102. && impostorJoint.joint === joint
  86103. && impostorJoint.mainImpostor === mainImpostor);
  86104. });
  86105. if (matchingJoints.length) {
  86106. this._physicsPlugin.removeJoint(matchingJoints[0]);
  86107. //TODO remove it from the list as well
  86108. }
  86109. };
  86110. /**
  86111. * Called by the scene. no need to call it.
  86112. */
  86113. PhysicsEngine.prototype._step = function (delta) {
  86114. var _this = this;
  86115. //check if any mesh has no body / requires an update
  86116. this._impostors.forEach(function (impostor) {
  86117. if (impostor.isBodyInitRequired()) {
  86118. _this._physicsPlugin.generatePhysicsBody(impostor);
  86119. }
  86120. });
  86121. if (delta > 0.1) {
  86122. delta = 0.1;
  86123. }
  86124. else if (delta <= 0) {
  86125. delta = 1.0 / 60.0;
  86126. }
  86127. this._physicsPlugin.executeStep(delta, this._impostors);
  86128. };
  86129. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  86130. return this._physicsPlugin;
  86131. };
  86132. PhysicsEngine.prototype.getImpostors = function () {
  86133. return this._impostors;
  86134. };
  86135. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  86136. for (var i = 0; i < this._impostors.length; ++i) {
  86137. if (this._impostors[i].object === object) {
  86138. return this._impostors[i];
  86139. }
  86140. }
  86141. return null;
  86142. };
  86143. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  86144. for (var i = 0; i < this._impostors.length; ++i) {
  86145. if (this._impostors[i].physicsBody === body) {
  86146. return this._impostors[i];
  86147. }
  86148. }
  86149. return null;
  86150. };
  86151. // Statics
  86152. PhysicsEngine.Epsilon = 0.001;
  86153. return PhysicsEngine;
  86154. }());
  86155. BABYLON.PhysicsEngine = PhysicsEngine;
  86156. })(BABYLON || (BABYLON = {}));
  86157. //# sourceMappingURL=babylon.physicsEngine.js.map
  86158. var BABYLON;
  86159. (function (BABYLON) {
  86160. var PhysicsHelper = /** @class */ (function () {
  86161. function PhysicsHelper(scene) {
  86162. this._scene = scene;
  86163. this._physicsEngine = this._scene.getPhysicsEngine();
  86164. if (!this._physicsEngine) {
  86165. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  86166. }
  86167. }
  86168. /**
  86169. * @param {Vector3} origin the origin of the explosion
  86170. * @param {number} radius the explosion radius
  86171. * @param {number} strength the explosion strength
  86172. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86173. */
  86174. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  86175. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86176. if (!this._physicsEngine) {
  86177. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  86178. return null;
  86179. }
  86180. var impostors = this._physicsEngine.getImpostors();
  86181. if (impostors.length === 0) {
  86182. return null;
  86183. }
  86184. var event = new PhysicsRadialExplosionEvent(this._scene);
  86185. impostors.forEach(function (impostor) {
  86186. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86187. if (!impostorForceAndContactPoint) {
  86188. return;
  86189. }
  86190. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86191. });
  86192. event.dispose(false);
  86193. return event;
  86194. };
  86195. /**
  86196. * @param {Vector3} origin the origin of the explosion
  86197. * @param {number} radius the explosion radius
  86198. * @param {number} strength the explosion strength
  86199. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86200. */
  86201. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  86202. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86203. if (!this._physicsEngine) {
  86204. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86205. return null;
  86206. }
  86207. var impostors = this._physicsEngine.getImpostors();
  86208. if (impostors.length === 0) {
  86209. return null;
  86210. }
  86211. var event = new PhysicsRadialExplosionEvent(this._scene);
  86212. impostors.forEach(function (impostor) {
  86213. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86214. if (!impostorForceAndContactPoint) {
  86215. return;
  86216. }
  86217. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86218. });
  86219. event.dispose(false);
  86220. return event;
  86221. };
  86222. /**
  86223. * @param {Vector3} origin the origin of the explosion
  86224. * @param {number} radius the explosion radius
  86225. * @param {number} strength the explosion strength
  86226. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86227. */
  86228. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  86229. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86230. if (!this._physicsEngine) {
  86231. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86232. return null;
  86233. }
  86234. var impostors = this._physicsEngine.getImpostors();
  86235. if (impostors.length === 0) {
  86236. return null;
  86237. }
  86238. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  86239. event.dispose(false);
  86240. return event;
  86241. };
  86242. /**
  86243. * @param {Vector3} origin the origin of the updraft
  86244. * @param {number} radius the radius of the updraft
  86245. * @param {number} strength the strength of the updraft
  86246. * @param {number} height the height of the updraft
  86247. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  86248. */
  86249. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  86250. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  86251. if (!this._physicsEngine) {
  86252. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86253. return null;
  86254. }
  86255. if (this._physicsEngine.getImpostors().length === 0) {
  86256. return null;
  86257. }
  86258. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  86259. event.dispose(false);
  86260. return event;
  86261. };
  86262. /**
  86263. * @param {Vector3} origin the of the vortex
  86264. * @param {number} radius the radius of the vortex
  86265. * @param {number} strength the strength of the vortex
  86266. * @param {number} height the height of the vortex
  86267. */
  86268. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  86269. if (!this._physicsEngine) {
  86270. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86271. return null;
  86272. }
  86273. if (this._physicsEngine.getImpostors().length === 0) {
  86274. return null;
  86275. }
  86276. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  86277. event.dispose(false);
  86278. return event;
  86279. };
  86280. return PhysicsHelper;
  86281. }());
  86282. BABYLON.PhysicsHelper = PhysicsHelper;
  86283. /***** Radial explosion *****/
  86284. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  86285. function PhysicsRadialExplosionEvent(scene) {
  86286. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  86287. this._rays = [];
  86288. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  86289. this._scene = scene;
  86290. }
  86291. /**
  86292. * Returns the data related to the radial explosion event (sphere & rays).
  86293. * @returns {PhysicsRadialExplosionEventData}
  86294. */
  86295. PhysicsRadialExplosionEvent.prototype.getData = function () {
  86296. this._dataFetched = true;
  86297. return {
  86298. sphere: this._sphere,
  86299. rays: this._rays,
  86300. };
  86301. };
  86302. /**
  86303. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  86304. * @param impostor
  86305. * @param {Vector3} origin the origin of the explosion
  86306. * @param {number} radius the explosion radius
  86307. * @param {number} strength the explosion strength
  86308. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  86309. * @returns {Nullable<PhysicsForceAndContactPoint>}
  86310. */
  86311. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  86312. if (impostor.mass === 0) {
  86313. return null;
  86314. }
  86315. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  86316. return null;
  86317. }
  86318. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86319. return null;
  86320. }
  86321. var impostorObjectCenter = impostor.getObjectCenter();
  86322. var direction = impostorObjectCenter.subtract(origin);
  86323. var ray = new BABYLON.Ray(origin, direction, radius);
  86324. this._rays.push(ray);
  86325. var hit = ray.intersectsMesh(impostor.object);
  86326. var contactPoint = hit.pickedPoint;
  86327. if (!contactPoint) {
  86328. return null;
  86329. }
  86330. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  86331. if (distanceFromOrigin > radius) {
  86332. return null;
  86333. }
  86334. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  86335. ? strength
  86336. : strength * (1 - (distanceFromOrigin / radius));
  86337. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86338. return { force: force, contactPoint: contactPoint };
  86339. };
  86340. /**
  86341. * Disposes the sphere.
  86342. * @param {bolean} force
  86343. */
  86344. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  86345. var _this = this;
  86346. if (force === void 0) { force = true; }
  86347. if (force) {
  86348. this._sphere.dispose();
  86349. }
  86350. else {
  86351. setTimeout(function () {
  86352. if (!_this._dataFetched) {
  86353. _this._sphere.dispose();
  86354. }
  86355. }, 0);
  86356. }
  86357. };
  86358. /*** Helpers ***/
  86359. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  86360. if (!this._sphere) {
  86361. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  86362. this._sphere.isVisible = false;
  86363. }
  86364. };
  86365. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  86366. var impostorObject = impostor.object;
  86367. this._prepareSphere();
  86368. this._sphere.position = origin;
  86369. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  86370. this._sphere._updateBoundingInfo();
  86371. this._sphere.computeWorldMatrix(true);
  86372. return this._sphere.intersectsMesh(impostorObject, true);
  86373. };
  86374. return PhysicsRadialExplosionEvent;
  86375. }());
  86376. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  86377. /***** Gravitational Field *****/
  86378. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  86379. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  86380. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86381. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86382. this._physicsHelper = physicsHelper;
  86383. this._scene = scene;
  86384. this._origin = origin;
  86385. this._radius = radius;
  86386. this._strength = strength;
  86387. this._falloff = falloff;
  86388. this._tickCallback = this._tick.bind(this);
  86389. }
  86390. /**
  86391. * Returns the data related to the gravitational field event (sphere).
  86392. * @returns {PhysicsGravitationalFieldEventData}
  86393. */
  86394. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  86395. this._dataFetched = true;
  86396. return {
  86397. sphere: this._sphere,
  86398. };
  86399. };
  86400. /**
  86401. * Enables the gravitational field.
  86402. */
  86403. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  86404. this._tickCallback.call(this);
  86405. this._scene.registerBeforeRender(this._tickCallback);
  86406. };
  86407. /**
  86408. * Disables the gravitational field.
  86409. */
  86410. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  86411. this._scene.unregisterBeforeRender(this._tickCallback);
  86412. };
  86413. /**
  86414. * Disposes the sphere.
  86415. * @param {bolean} force
  86416. */
  86417. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  86418. var _this = this;
  86419. if (force === void 0) { force = true; }
  86420. if (force) {
  86421. this._sphere.dispose();
  86422. }
  86423. else {
  86424. setTimeout(function () {
  86425. if (!_this._dataFetched) {
  86426. _this._sphere.dispose();
  86427. }
  86428. }, 0);
  86429. }
  86430. };
  86431. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  86432. // Since the params won't change, we fetch the event only once
  86433. if (this._sphere) {
  86434. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86435. }
  86436. else {
  86437. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86438. if (radialExplosionEvent) {
  86439. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  86440. }
  86441. }
  86442. };
  86443. return PhysicsGravitationalFieldEvent;
  86444. }());
  86445. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86446. /***** Updraft *****/
  86447. var PhysicsUpdraftEvent = /** @class */ (function () {
  86448. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86449. this._scene = _scene;
  86450. this._origin = _origin;
  86451. this._radius = _radius;
  86452. this._strength = _strength;
  86453. this._height = _height;
  86454. this._updraftMode = _updraftMode;
  86455. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86456. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86457. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86458. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86459. this._physicsEngine = this._scene.getPhysicsEngine();
  86460. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86461. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86462. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86463. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86464. }
  86465. this._tickCallback = this._tick.bind(this);
  86466. }
  86467. /**
  86468. * Returns the data related to the updraft event (cylinder).
  86469. * @returns {PhysicsUpdraftEventData}
  86470. */
  86471. PhysicsUpdraftEvent.prototype.getData = function () {
  86472. this._dataFetched = true;
  86473. return {
  86474. cylinder: this._cylinder,
  86475. };
  86476. };
  86477. /**
  86478. * Enables the updraft.
  86479. */
  86480. PhysicsUpdraftEvent.prototype.enable = function () {
  86481. this._tickCallback.call(this);
  86482. this._scene.registerBeforeRender(this._tickCallback);
  86483. };
  86484. /**
  86485. * Disables the cortex.
  86486. */
  86487. PhysicsUpdraftEvent.prototype.disable = function () {
  86488. this._scene.unregisterBeforeRender(this._tickCallback);
  86489. };
  86490. /**
  86491. * Disposes the sphere.
  86492. * @param {bolean} force
  86493. */
  86494. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86495. var _this = this;
  86496. if (force === void 0) { force = true; }
  86497. if (force) {
  86498. this._cylinder.dispose();
  86499. }
  86500. else {
  86501. setTimeout(function () {
  86502. if (!_this._dataFetched) {
  86503. _this._cylinder.dispose();
  86504. }
  86505. }, 0);
  86506. }
  86507. };
  86508. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86509. if (impostor.mass === 0) {
  86510. return null;
  86511. }
  86512. if (!this._intersectsWithCylinder(impostor)) {
  86513. return null;
  86514. }
  86515. var impostorObjectCenter = impostor.getObjectCenter();
  86516. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86517. var direction = this._originDirection;
  86518. }
  86519. else {
  86520. var direction = impostorObjectCenter.subtract(this._originTop);
  86521. }
  86522. var multiplier = this._strength * -1;
  86523. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86524. return { force: force, contactPoint: impostorObjectCenter };
  86525. };
  86526. PhysicsUpdraftEvent.prototype._tick = function () {
  86527. var _this = this;
  86528. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86529. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86530. if (!impostorForceAndContactPoint) {
  86531. return;
  86532. }
  86533. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86534. });
  86535. };
  86536. /*** Helpers ***/
  86537. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86538. if (!this._cylinder) {
  86539. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86540. height: this._height,
  86541. diameter: this._radius * 2,
  86542. }, this._scene);
  86543. this._cylinder.isVisible = false;
  86544. }
  86545. };
  86546. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86547. var impostorObject = impostor.object;
  86548. this._prepareCylinder();
  86549. this._cylinder.position = this._cylinderPosition;
  86550. return this._cylinder.intersectsMesh(impostorObject, true);
  86551. };
  86552. return PhysicsUpdraftEvent;
  86553. }());
  86554. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86555. /***** Vortex *****/
  86556. var PhysicsVortexEvent = /** @class */ (function () {
  86557. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86558. this._scene = _scene;
  86559. this._origin = _origin;
  86560. this._radius = _radius;
  86561. this._strength = _strength;
  86562. this._height = _height;
  86563. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86564. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86565. this._updraftMultiplier = 0.02;
  86566. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86567. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86568. this._physicsEngine = this._scene.getPhysicsEngine();
  86569. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86570. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86571. this._tickCallback = this._tick.bind(this);
  86572. }
  86573. /**
  86574. * Returns the data related to the vortex event (cylinder).
  86575. * @returns {PhysicsVortexEventData}
  86576. */
  86577. PhysicsVortexEvent.prototype.getData = function () {
  86578. this._dataFetched = true;
  86579. return {
  86580. cylinder: this._cylinder,
  86581. };
  86582. };
  86583. /**
  86584. * Enables the vortex.
  86585. */
  86586. PhysicsVortexEvent.prototype.enable = function () {
  86587. this._tickCallback.call(this);
  86588. this._scene.registerBeforeRender(this._tickCallback);
  86589. };
  86590. /**
  86591. * Disables the cortex.
  86592. */
  86593. PhysicsVortexEvent.prototype.disable = function () {
  86594. this._scene.unregisterBeforeRender(this._tickCallback);
  86595. };
  86596. /**
  86597. * Disposes the sphere.
  86598. * @param {bolean} force
  86599. */
  86600. PhysicsVortexEvent.prototype.dispose = function (force) {
  86601. var _this = this;
  86602. if (force === void 0) { force = true; }
  86603. if (force) {
  86604. this._cylinder.dispose();
  86605. }
  86606. else {
  86607. setTimeout(function () {
  86608. if (!_this._dataFetched) {
  86609. _this._cylinder.dispose();
  86610. }
  86611. }, 0);
  86612. }
  86613. };
  86614. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86615. if (impostor.mass === 0) {
  86616. return null;
  86617. }
  86618. if (!this._intersectsWithCylinder(impostor)) {
  86619. return null;
  86620. }
  86621. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86622. return null;
  86623. }
  86624. var impostorObjectCenter = impostor.getObjectCenter();
  86625. 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)
  86626. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86627. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86628. var hit = ray.intersectsMesh(impostor.object);
  86629. var contactPoint = hit.pickedPoint;
  86630. if (!contactPoint) {
  86631. return null;
  86632. }
  86633. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86634. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86635. var directionToOrigin = contactPoint.normalize();
  86636. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86637. directionToOrigin = directionToOrigin.negate();
  86638. }
  86639. // TODO: find a more physically based solution
  86640. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86641. var forceX = directionToOrigin.x * this._strength / 8;
  86642. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86643. var forceZ = directionToOrigin.z * this._strength / 8;
  86644. }
  86645. else {
  86646. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86647. var forceY = this._originTop.y * this._updraftMultiplier;
  86648. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86649. }
  86650. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86651. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86652. return { force: force, contactPoint: impostorObjectCenter };
  86653. };
  86654. PhysicsVortexEvent.prototype._tick = function () {
  86655. var _this = this;
  86656. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86657. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86658. if (!impostorForceAndContactPoint) {
  86659. return;
  86660. }
  86661. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86662. });
  86663. };
  86664. /*** Helpers ***/
  86665. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86666. if (!this._cylinder) {
  86667. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86668. height: this._height,
  86669. diameter: this._radius * 2,
  86670. }, this._scene);
  86671. this._cylinder.isVisible = false;
  86672. }
  86673. };
  86674. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86675. var impostorObject = impostor.object;
  86676. this._prepareCylinder();
  86677. this._cylinder.position = this._cylinderPosition;
  86678. return this._cylinder.intersectsMesh(impostorObject, true);
  86679. };
  86680. return PhysicsVortexEvent;
  86681. }());
  86682. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86683. /***** Enums *****/
  86684. /**
  86685. * The strenght of the force in correspondence to the distance of the affected object
  86686. */
  86687. var PhysicsRadialImpulseFalloff;
  86688. (function (PhysicsRadialImpulseFalloff) {
  86689. /** Defines that impulse is constant in strength across it's whole radius */
  86690. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86691. /** DEfines that impulse gets weaker if it's further from the origin */
  86692. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86693. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86694. /**
  86695. * The strenght of the force in correspondence to the distance of the affected object
  86696. */
  86697. var PhysicsUpdraftMode;
  86698. (function (PhysicsUpdraftMode) {
  86699. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86700. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86701. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86702. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86703. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86704. })(BABYLON || (BABYLON = {}));
  86705. //# sourceMappingURL=babylon.physicsHelper.js.map
  86706. var BABYLON;
  86707. (function (BABYLON) {
  86708. var CannonJSPlugin = /** @class */ (function () {
  86709. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86710. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86711. if (iterations === void 0) { iterations = 10; }
  86712. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86713. this.name = "CannonJSPlugin";
  86714. this._physicsMaterials = new Array();
  86715. this._fixedTimeStep = 1 / 60;
  86716. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86717. this.BJSCANNON = CANNON;
  86718. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86719. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86720. this._tmpPosition = BABYLON.Vector3.Zero();
  86721. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86722. this._tmpUnityRotation = new BABYLON.Quaternion();
  86723. if (!this.isSupported()) {
  86724. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86725. return;
  86726. }
  86727. this._extendNamespace();
  86728. this.world = new this.BJSCANNON.World();
  86729. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86730. this.world.solver.iterations = iterations;
  86731. }
  86732. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86733. this.world.gravity.copy(gravity);
  86734. };
  86735. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86736. this._fixedTimeStep = timeStep;
  86737. };
  86738. CannonJSPlugin.prototype.getTimeStep = function () {
  86739. return this._fixedTimeStep;
  86740. };
  86741. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86742. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86743. };
  86744. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86745. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86746. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86747. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86748. };
  86749. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86750. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86751. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86752. impostor.physicsBody.applyForce(impulse, worldPoint);
  86753. };
  86754. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86755. //parent-child relationship. Does this impostor has a parent impostor?
  86756. if (impostor.parent) {
  86757. if (impostor.physicsBody) {
  86758. this.removePhysicsBody(impostor);
  86759. //TODO is that needed?
  86760. impostor.forceUpdate();
  86761. }
  86762. return;
  86763. }
  86764. //should a new body be created for this impostor?
  86765. if (impostor.isBodyInitRequired()) {
  86766. var shape = this._createShape(impostor);
  86767. //unregister events, if body is being changed
  86768. var oldBody = impostor.physicsBody;
  86769. if (oldBody) {
  86770. this.removePhysicsBody(impostor);
  86771. }
  86772. //create the body and material
  86773. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86774. var bodyCreationObject = {
  86775. mass: impostor.getParam("mass"),
  86776. material: material
  86777. };
  86778. // A simple extend, in case native options were used.
  86779. var nativeOptions = impostor.getParam("nativeOptions");
  86780. for (var key in nativeOptions) {
  86781. if (nativeOptions.hasOwnProperty(key)) {
  86782. bodyCreationObject[key] = nativeOptions[key];
  86783. }
  86784. }
  86785. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86786. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86787. this.world.addEventListener("preStep", impostor.beforeStep);
  86788. this.world.addEventListener("postStep", impostor.afterStep);
  86789. impostor.physicsBody.addShape(shape);
  86790. this.world.add(impostor.physicsBody);
  86791. //try to keep the body moving in the right direction by taking old properties.
  86792. //Should be tested!
  86793. if (oldBody) {
  86794. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86795. impostor.physicsBody[param].copy(oldBody[param]);
  86796. });
  86797. }
  86798. this._processChildMeshes(impostor);
  86799. }
  86800. //now update the body's transformation
  86801. this._updatePhysicsBodyTransformation(impostor);
  86802. };
  86803. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86804. var _this = this;
  86805. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86806. var currentRotation = mainImpostor.object.rotationQuaternion;
  86807. if (meshChildren.length) {
  86808. var processMesh = function (localPosition, mesh) {
  86809. if (!currentRotation || !mesh.rotationQuaternion) {
  86810. return;
  86811. }
  86812. var childImpostor = mesh.getPhysicsImpostor();
  86813. if (childImpostor) {
  86814. var parent = childImpostor.parent;
  86815. if (parent !== mainImpostor) {
  86816. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86817. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86818. if (childImpostor.physicsBody) {
  86819. _this.removePhysicsBody(childImpostor);
  86820. childImpostor.physicsBody = null;
  86821. }
  86822. childImpostor.parent = mainImpostor;
  86823. childImpostor.resetUpdateFlags();
  86824. 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));
  86825. //Add the mass of the children.
  86826. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86827. }
  86828. }
  86829. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86830. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86831. };
  86832. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86833. }
  86834. };
  86835. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86836. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86837. this.world.removeEventListener("preStep", impostor.beforeStep);
  86838. this.world.removeEventListener("postStep", impostor.afterStep);
  86839. this.world.remove(impostor.physicsBody);
  86840. };
  86841. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86842. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86843. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86844. if (!mainBody || !connectedBody) {
  86845. return;
  86846. }
  86847. var constraint;
  86848. var jointData = impostorJoint.joint.jointData;
  86849. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86850. var constraintData = {
  86851. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86852. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86853. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86854. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86855. maxForce: jointData.nativeParams.maxForce,
  86856. collideConnected: !!jointData.collision
  86857. };
  86858. switch (impostorJoint.joint.type) {
  86859. case BABYLON.PhysicsJoint.HingeJoint:
  86860. case BABYLON.PhysicsJoint.Hinge2Joint:
  86861. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86862. break;
  86863. case BABYLON.PhysicsJoint.DistanceJoint:
  86864. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86865. break;
  86866. case BABYLON.PhysicsJoint.SpringJoint:
  86867. var springData = jointData;
  86868. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86869. restLength: springData.length,
  86870. stiffness: springData.stiffness,
  86871. damping: springData.damping,
  86872. localAnchorA: constraintData.pivotA,
  86873. localAnchorB: constraintData.pivotB
  86874. });
  86875. break;
  86876. case BABYLON.PhysicsJoint.LockJoint:
  86877. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86878. break;
  86879. case BABYLON.PhysicsJoint.PointToPointJoint:
  86880. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86881. default:
  86882. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86883. break;
  86884. }
  86885. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86886. constraint.collideConnected = !!jointData.collision;
  86887. impostorJoint.joint.physicsJoint = constraint;
  86888. //don't add spring as constraint, as it is not one.
  86889. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86890. this.world.addConstraint(constraint);
  86891. }
  86892. else {
  86893. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86894. constraint.applyForce();
  86895. });
  86896. }
  86897. };
  86898. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86899. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86900. };
  86901. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86902. var index;
  86903. var mat;
  86904. for (index = 0; index < this._physicsMaterials.length; index++) {
  86905. mat = this._physicsMaterials[index];
  86906. if (mat.friction === friction && mat.restitution === restitution) {
  86907. return mat;
  86908. }
  86909. }
  86910. var currentMat = new this.BJSCANNON.Material(name);
  86911. currentMat.friction = friction;
  86912. currentMat.restitution = restitution;
  86913. this._physicsMaterials.push(currentMat);
  86914. return currentMat;
  86915. };
  86916. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86917. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86918. };
  86919. CannonJSPlugin.prototype._createShape = function (impostor) {
  86920. var object = impostor.object;
  86921. var returnValue;
  86922. var extendSize = impostor.getObjectExtendSize();
  86923. switch (impostor.type) {
  86924. case BABYLON.PhysicsImpostor.SphereImpostor:
  86925. var radiusX = extendSize.x;
  86926. var radiusY = extendSize.y;
  86927. var radiusZ = extendSize.z;
  86928. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86929. break;
  86930. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86931. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86932. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86933. break;
  86934. case BABYLON.PhysicsImpostor.BoxImpostor:
  86935. var box = extendSize.scale(0.5);
  86936. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86937. break;
  86938. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86939. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86940. returnValue = new this.BJSCANNON.Plane();
  86941. break;
  86942. case BABYLON.PhysicsImpostor.MeshImpostor:
  86943. // should transform the vertex data to world coordinates!!
  86944. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86945. var rawFaces = object.getIndices ? object.getIndices() : [];
  86946. if (!rawVerts)
  86947. return;
  86948. // get only scale! so the object could transform correctly.
  86949. var oldPosition = object.position.clone();
  86950. var oldRotation = object.rotation && object.rotation.clone();
  86951. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86952. object.position.copyFromFloats(0, 0, 0);
  86953. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86954. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86955. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86956. var transform = object.computeWorldMatrix(true);
  86957. // convert rawVerts to object space
  86958. var temp = new Array();
  86959. var index;
  86960. for (index = 0; index < rawVerts.length; index += 3) {
  86961. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86962. }
  86963. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86964. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86965. //now set back the transformation!
  86966. object.position.copyFrom(oldPosition);
  86967. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86968. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86969. break;
  86970. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86971. var oldPosition2 = object.position.clone();
  86972. var oldRotation2 = object.rotation && object.rotation.clone();
  86973. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86974. object.position.copyFromFloats(0, 0, 0);
  86975. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86976. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86977. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86978. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86979. returnValue = this._createHeightmap(object);
  86980. object.position.copyFrom(oldPosition2);
  86981. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86982. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86983. object.computeWorldMatrix(true);
  86984. break;
  86985. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86986. returnValue = new this.BJSCANNON.Particle();
  86987. break;
  86988. }
  86989. return returnValue;
  86990. };
  86991. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86992. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86993. var transform = object.computeWorldMatrix(true);
  86994. // convert rawVerts to object space
  86995. var temp = new Array();
  86996. var index;
  86997. for (index = 0; index < pos.length; index += 3) {
  86998. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86999. }
  87000. pos = temp;
  87001. var matrix = new Array();
  87002. //For now pointDepth will not be used and will be automatically calculated.
  87003. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  87004. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  87005. var boundingInfo = object.getBoundingInfo();
  87006. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  87007. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  87008. var elementSize = dim * 2 / arraySize;
  87009. for (var i = 0; i < pos.length; i = i + 3) {
  87010. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  87011. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  87012. var y = -pos[i + 2] + minY;
  87013. if (!matrix[x]) {
  87014. matrix[x] = [];
  87015. }
  87016. if (!matrix[x][z]) {
  87017. matrix[x][z] = y;
  87018. }
  87019. matrix[x][z] = Math.max(y, matrix[x][z]);
  87020. }
  87021. for (var x = 0; x <= arraySize; ++x) {
  87022. if (!matrix[x]) {
  87023. var loc = 1;
  87024. while (!matrix[(x + loc) % arraySize]) {
  87025. loc++;
  87026. }
  87027. matrix[x] = matrix[(x + loc) % arraySize].slice();
  87028. //console.log("missing x", x);
  87029. }
  87030. for (var z = 0; z <= arraySize; ++z) {
  87031. if (!matrix[x][z]) {
  87032. var loc = 1;
  87033. var newValue;
  87034. while (newValue === undefined) {
  87035. newValue = matrix[x][(z + loc++) % arraySize];
  87036. }
  87037. matrix[x][z] = newValue;
  87038. }
  87039. }
  87040. }
  87041. var shape = new this.BJSCANNON.Heightfield(matrix, {
  87042. elementSize: elementSize
  87043. });
  87044. //For future reference, needed for body transformation
  87045. shape.minY = minY;
  87046. return shape;
  87047. };
  87048. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  87049. var object = impostor.object;
  87050. //make sure it is updated...
  87051. object.computeWorldMatrix && object.computeWorldMatrix(true);
  87052. // The delta between the mesh position and the mesh bounding box center
  87053. var bInfo = object.getBoundingInfo();
  87054. if (!bInfo)
  87055. return;
  87056. var center = impostor.getObjectCenter();
  87057. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  87058. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  87059. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  87060. this._tmpPosition.copyFrom(center);
  87061. var quaternion = object.rotationQuaternion;
  87062. if (!quaternion) {
  87063. return;
  87064. }
  87065. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  87066. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  87067. //-90 DEG in X, precalculated
  87068. quaternion = quaternion.multiply(this._minus90X);
  87069. //Invert! (Precalculated, 90 deg in X)
  87070. //No need to clone. this will never change.
  87071. impostor.setDeltaRotation(this._plus90X);
  87072. }
  87073. //If it is a heightfield, if should be centered.
  87074. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  87075. var mesh = object;
  87076. var boundingInfo = mesh.getBoundingInfo();
  87077. //calculate the correct body position:
  87078. var rotationQuaternion = mesh.rotationQuaternion;
  87079. mesh.rotationQuaternion = this._tmpUnityRotation;
  87080. mesh.computeWorldMatrix(true);
  87081. //get original center with no rotation
  87082. var c = center.clone();
  87083. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  87084. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  87085. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  87086. mesh.setPreTransformMatrix(p);
  87087. mesh.computeWorldMatrix(true);
  87088. //calculate the translation
  87089. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  87090. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  87091. //add it inverted to the delta
  87092. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  87093. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  87094. //rotation is back
  87095. mesh.rotationQuaternion = rotationQuaternion;
  87096. mesh.setPreTransformMatrix(oldPivot);
  87097. mesh.computeWorldMatrix(true);
  87098. }
  87099. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  87100. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  87101. //this._tmpPosition.copyFrom(object.position);
  87102. }
  87103. impostor.setDeltaPosition(this._tmpDeltaPosition);
  87104. //Now update the impostor object
  87105. impostor.physicsBody.position.copy(this._tmpPosition);
  87106. impostor.physicsBody.quaternion.copy(quaternion);
  87107. };
  87108. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87109. impostor.object.position.copyFrom(impostor.physicsBody.position);
  87110. if (impostor.object.rotationQuaternion) {
  87111. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  87112. }
  87113. };
  87114. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87115. impostor.physicsBody.position.copy(newPosition);
  87116. impostor.physicsBody.quaternion.copy(newRotation);
  87117. };
  87118. CannonJSPlugin.prototype.isSupported = function () {
  87119. return this.BJSCANNON !== undefined;
  87120. };
  87121. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87122. impostor.physicsBody.velocity.copy(velocity);
  87123. };
  87124. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87125. impostor.physicsBody.angularVelocity.copy(velocity);
  87126. };
  87127. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87128. var v = impostor.physicsBody.velocity;
  87129. if (!v) {
  87130. return null;
  87131. }
  87132. return new BABYLON.Vector3(v.x, v.y, v.z);
  87133. };
  87134. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87135. var v = impostor.physicsBody.angularVelocity;
  87136. if (!v) {
  87137. return null;
  87138. }
  87139. return new BABYLON.Vector3(v.x, v.y, v.z);
  87140. };
  87141. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87142. impostor.physicsBody.mass = mass;
  87143. impostor.physicsBody.updateMassProperties();
  87144. };
  87145. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  87146. return impostor.physicsBody.mass;
  87147. };
  87148. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  87149. return impostor.physicsBody.material.friction;
  87150. };
  87151. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87152. impostor.physicsBody.material.friction = friction;
  87153. };
  87154. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87155. return impostor.physicsBody.material.restitution;
  87156. };
  87157. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87158. impostor.physicsBody.material.restitution = restitution;
  87159. };
  87160. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  87161. impostor.physicsBody.sleep();
  87162. };
  87163. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  87164. impostor.physicsBody.wakeUp();
  87165. };
  87166. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87167. joint.physicsJoint.distance = maxDistance;
  87168. };
  87169. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87170. // if (!motorIndex) {
  87171. // joint.physicsJoint.enableMotor();
  87172. // }
  87173. // }
  87174. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87175. // if (!motorIndex) {
  87176. // joint.physicsJoint.disableMotor();
  87177. // }
  87178. // }
  87179. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87180. if (!motorIndex) {
  87181. joint.physicsJoint.enableMotor();
  87182. joint.physicsJoint.setMotorSpeed(speed);
  87183. if (maxForce) {
  87184. this.setLimit(joint, maxForce);
  87185. }
  87186. }
  87187. };
  87188. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  87189. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  87190. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  87191. };
  87192. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87193. var body = impostor.physicsBody;
  87194. mesh.position.x = body.position.x;
  87195. mesh.position.y = body.position.y;
  87196. mesh.position.z = body.position.z;
  87197. if (mesh.rotationQuaternion) {
  87198. mesh.rotationQuaternion.x = body.quaternion.x;
  87199. mesh.rotationQuaternion.y = body.quaternion.y;
  87200. mesh.rotationQuaternion.z = body.quaternion.z;
  87201. mesh.rotationQuaternion.w = body.quaternion.w;
  87202. }
  87203. };
  87204. CannonJSPlugin.prototype.getRadius = function (impostor) {
  87205. var shape = impostor.physicsBody.shapes[0];
  87206. return shape.boundingSphereRadius;
  87207. };
  87208. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87209. var shape = impostor.physicsBody.shapes[0];
  87210. result.x = shape.halfExtents.x * 2;
  87211. result.y = shape.halfExtents.y * 2;
  87212. result.z = shape.halfExtents.z * 2;
  87213. };
  87214. CannonJSPlugin.prototype.dispose = function () {
  87215. };
  87216. CannonJSPlugin.prototype._extendNamespace = function () {
  87217. //this will force cannon to execute at least one step when using interpolation
  87218. var step_tmp1 = new this.BJSCANNON.Vec3();
  87219. var Engine = this.BJSCANNON;
  87220. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  87221. maxSubSteps = maxSubSteps || 10;
  87222. timeSinceLastCalled = timeSinceLastCalled || 0;
  87223. if (timeSinceLastCalled === 0) {
  87224. this.internalStep(dt);
  87225. this.time += dt;
  87226. }
  87227. else {
  87228. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  87229. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  87230. var t0 = performance.now();
  87231. for (var i = 0; i !== internalSteps; i++) {
  87232. this.internalStep(dt);
  87233. if (performance.now() - t0 > dt * 1000) {
  87234. break;
  87235. }
  87236. }
  87237. this.time += timeSinceLastCalled;
  87238. var h = this.time % dt;
  87239. var h_div_dt = h / dt;
  87240. var interpvelo = step_tmp1;
  87241. var bodies = this.bodies;
  87242. for (var j = 0; j !== bodies.length; j++) {
  87243. var b = bodies[j];
  87244. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  87245. b.position.vsub(b.previousPosition, interpvelo);
  87246. interpvelo.scale(h_div_dt, interpvelo);
  87247. b.position.vadd(interpvelo, b.interpolatedPosition);
  87248. }
  87249. else {
  87250. b.interpolatedPosition.copy(b.position);
  87251. b.interpolatedQuaternion.copy(b.quaternion);
  87252. }
  87253. }
  87254. }
  87255. };
  87256. };
  87257. return CannonJSPlugin;
  87258. }());
  87259. BABYLON.CannonJSPlugin = CannonJSPlugin;
  87260. })(BABYLON || (BABYLON = {}));
  87261. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  87262. var BABYLON;
  87263. (function (BABYLON) {
  87264. var OimoJSPlugin = /** @class */ (function () {
  87265. function OimoJSPlugin(iterations) {
  87266. this.name = "OimoJSPlugin";
  87267. this._tmpImpostorsArray = [];
  87268. this._tmpPositionVector = BABYLON.Vector3.Zero();
  87269. this.BJSOIMO = OIMO;
  87270. this.world = new this.BJSOIMO.World({
  87271. iterations: iterations
  87272. });
  87273. this.world.clear();
  87274. }
  87275. OimoJSPlugin.prototype.setGravity = function (gravity) {
  87276. this.world.gravity.copy(gravity);
  87277. };
  87278. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  87279. this.world.timeStep = timeStep;
  87280. };
  87281. OimoJSPlugin.prototype.getTimeStep = function () {
  87282. return this.world.timeStep;
  87283. };
  87284. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  87285. var _this = this;
  87286. impostors.forEach(function (impostor) {
  87287. impostor.beforeStep();
  87288. });
  87289. this.world.step();
  87290. impostors.forEach(function (impostor) {
  87291. impostor.afterStep();
  87292. //update the ordered impostors array
  87293. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  87294. });
  87295. //check for collisions
  87296. var contact = this.world.contacts;
  87297. while (contact !== null) {
  87298. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  87299. contact = contact.next;
  87300. continue;
  87301. }
  87302. //is this body colliding with any other? get the impostor
  87303. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  87304. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  87305. if (!mainImpostor || !collidingImpostor) {
  87306. contact = contact.next;
  87307. continue;
  87308. }
  87309. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  87310. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  87311. contact = contact.next;
  87312. }
  87313. };
  87314. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87315. var mass = impostor.physicsBody.mass;
  87316. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  87317. };
  87318. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87319. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  87320. this.applyImpulse(impostor, force, contactPoint);
  87321. };
  87322. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87323. var _this = this;
  87324. //parent-child relationship. Does this impostor has a parent impostor?
  87325. if (impostor.parent) {
  87326. if (impostor.physicsBody) {
  87327. this.removePhysicsBody(impostor);
  87328. //TODO is that needed?
  87329. impostor.forceUpdate();
  87330. }
  87331. return;
  87332. }
  87333. if (impostor.isBodyInitRequired()) {
  87334. var bodyConfig = {
  87335. name: impostor.uniqueId,
  87336. //Oimo must have mass, also for static objects.
  87337. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87338. size: [],
  87339. type: [],
  87340. pos: [],
  87341. posShape: [],
  87342. rot: [],
  87343. rotShape: [],
  87344. move: impostor.getParam("mass") !== 0,
  87345. density: impostor.getParam("mass"),
  87346. friction: impostor.getParam("friction"),
  87347. restitution: impostor.getParam("restitution"),
  87348. //Supporting older versions of Oimo
  87349. world: this.world
  87350. };
  87351. var impostors = [impostor];
  87352. var addToArray = function (parent) {
  87353. if (!parent.getChildMeshes)
  87354. return;
  87355. parent.getChildMeshes().forEach(function (m) {
  87356. if (m.physicsImpostor) {
  87357. impostors.push(m.physicsImpostor);
  87358. //m.physicsImpostor._init();
  87359. }
  87360. });
  87361. };
  87362. addToArray(impostor.object);
  87363. var checkWithEpsilon_1 = function (value) {
  87364. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  87365. };
  87366. var globalQuaternion_1 = new BABYLON.Quaternion();
  87367. impostors.forEach(function (i) {
  87368. if (!i.object.rotationQuaternion) {
  87369. return;
  87370. }
  87371. //get the correct bounding box
  87372. var oldQuaternion = i.object.rotationQuaternion;
  87373. globalQuaternion_1 = oldQuaternion.clone();
  87374. var rot = oldQuaternion.toEulerAngles();
  87375. var extendSize = i.getObjectExtendSize();
  87376. var radToDeg = 57.295779513082320876;
  87377. if (i === impostor) {
  87378. var center = impostor.getObjectCenter();
  87379. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  87380. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  87381. //Can also use Array.prototype.push.apply
  87382. bodyConfig.pos.push(center.x);
  87383. bodyConfig.pos.push(center.y);
  87384. bodyConfig.pos.push(center.z);
  87385. bodyConfig.posShape.push(0, 0, 0);
  87386. //tmp solution
  87387. bodyConfig.rot.push(0);
  87388. bodyConfig.rot.push(0);
  87389. bodyConfig.rot.push(0);
  87390. bodyConfig.rotShape.push(0, 0, 0);
  87391. }
  87392. else {
  87393. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  87394. bodyConfig.posShape.push(localPosition.x);
  87395. bodyConfig.posShape.push(localPosition.y);
  87396. bodyConfig.posShape.push(localPosition.z);
  87397. bodyConfig.pos.push(0, 0, 0);
  87398. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  87399. bodyConfig.rot.push(0);
  87400. bodyConfig.rot.push(0);
  87401. bodyConfig.rot.push(0);
  87402. bodyConfig.rotShape.push(rot.x * radToDeg);
  87403. bodyConfig.rotShape.push(rot.y * radToDeg);
  87404. bodyConfig.rotShape.push(rot.z * radToDeg);
  87405. }
  87406. // register mesh
  87407. switch (i.type) {
  87408. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87409. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  87410. case BABYLON.PhysicsImpostor.SphereImpostor:
  87411. var radiusX = extendSize.x;
  87412. var radiusY = extendSize.y;
  87413. var radiusZ = extendSize.z;
  87414. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  87415. bodyConfig.type.push('sphere');
  87416. //due to the way oimo works with compounds, add 3 times
  87417. bodyConfig.size.push(size);
  87418. bodyConfig.size.push(size);
  87419. bodyConfig.size.push(size);
  87420. break;
  87421. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87422. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  87423. var sizeY = checkWithEpsilon_1(extendSize.y);
  87424. bodyConfig.type.push('cylinder');
  87425. bodyConfig.size.push(sizeX);
  87426. bodyConfig.size.push(sizeY);
  87427. //due to the way oimo works with compounds, add one more value.
  87428. bodyConfig.size.push(sizeY);
  87429. break;
  87430. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87431. case BABYLON.PhysicsImpostor.BoxImpostor:
  87432. default:
  87433. var sizeX = checkWithEpsilon_1(extendSize.x);
  87434. var sizeY = checkWithEpsilon_1(extendSize.y);
  87435. var sizeZ = checkWithEpsilon_1(extendSize.z);
  87436. bodyConfig.type.push('box');
  87437. //if (i === impostor) {
  87438. bodyConfig.size.push(sizeX);
  87439. bodyConfig.size.push(sizeY);
  87440. bodyConfig.size.push(sizeZ);
  87441. //} else {
  87442. // bodyConfig.size.push(0,0,0);
  87443. //}
  87444. break;
  87445. }
  87446. //actually not needed, but hey...
  87447. i.object.rotationQuaternion = oldQuaternion;
  87448. });
  87449. impostor.physicsBody = this.world.add(bodyConfig);
  87450. // set the quaternion, ignoring the previously defined (euler) rotation
  87451. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87452. // update with delta 0, so the body will reveive the new rotation.
  87453. impostor.physicsBody.updatePosition(0);
  87454. }
  87455. else {
  87456. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87457. }
  87458. impostor.setDeltaPosition(this._tmpPositionVector);
  87459. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87460. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87461. };
  87462. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87463. //impostor.physicsBody.dispose();
  87464. //Same as : (older oimo versions)
  87465. this.world.removeRigidBody(impostor.physicsBody);
  87466. };
  87467. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87468. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87469. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87470. if (!mainBody || !connectedBody) {
  87471. return;
  87472. }
  87473. var jointData = impostorJoint.joint.jointData;
  87474. var options = jointData.nativeParams || {};
  87475. var type;
  87476. var nativeJointData = {
  87477. body1: mainBody,
  87478. body2: connectedBody,
  87479. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87480. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87481. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87482. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87483. min: options.min,
  87484. max: options.max,
  87485. collision: options.collision || jointData.collision,
  87486. spring: options.spring,
  87487. //supporting older version of Oimo
  87488. world: this.world
  87489. };
  87490. switch (impostorJoint.joint.type) {
  87491. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87492. type = "jointBall";
  87493. break;
  87494. case BABYLON.PhysicsJoint.SpringJoint:
  87495. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87496. var springData = jointData;
  87497. nativeJointData.min = springData.length || nativeJointData.min;
  87498. //Max should also be set, just make sure it is at least min
  87499. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87500. case BABYLON.PhysicsJoint.DistanceJoint:
  87501. type = "jointDistance";
  87502. nativeJointData.max = jointData.maxDistance;
  87503. break;
  87504. case BABYLON.PhysicsJoint.PrismaticJoint:
  87505. type = "jointPrisme";
  87506. break;
  87507. case BABYLON.PhysicsJoint.SliderJoint:
  87508. type = "jointSlide";
  87509. break;
  87510. case BABYLON.PhysicsJoint.WheelJoint:
  87511. type = "jointWheel";
  87512. break;
  87513. case BABYLON.PhysicsJoint.HingeJoint:
  87514. default:
  87515. type = "jointHinge";
  87516. break;
  87517. }
  87518. nativeJointData.type = type;
  87519. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87520. };
  87521. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87522. //Bug in Oimo prevents us from disposing a joint in the playground
  87523. //joint.joint.physicsJoint.dispose();
  87524. //So we will bruteforce it!
  87525. try {
  87526. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87527. }
  87528. catch (e) {
  87529. BABYLON.Tools.Warn(e);
  87530. }
  87531. };
  87532. OimoJSPlugin.prototype.isSupported = function () {
  87533. return this.BJSOIMO !== undefined;
  87534. };
  87535. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87536. if (!impostor.physicsBody.sleeping) {
  87537. //TODO check that
  87538. /*if (impostor.physicsBody.shapes.next) {
  87539. var parentShape = this._getLastShape(impostor.physicsBody);
  87540. impostor.object.position.copyFrom(parentShape.position);
  87541. console.log(parentShape.position);
  87542. } else {*/
  87543. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87544. //}
  87545. if (impostor.object.rotationQuaternion) {
  87546. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87547. }
  87548. }
  87549. };
  87550. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87551. var body = impostor.physicsBody;
  87552. body.position.copy(newPosition);
  87553. body.orientation.copy(newRotation);
  87554. body.syncShapes();
  87555. body.awake();
  87556. };
  87557. /*private _getLastShape(body: any): any {
  87558. var lastShape = body.shapes;
  87559. while (lastShape.next) {
  87560. lastShape = lastShape.next;
  87561. }
  87562. return lastShape;
  87563. }*/
  87564. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87565. impostor.physicsBody.linearVelocity.copy(velocity);
  87566. };
  87567. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87568. impostor.physicsBody.angularVelocity.copy(velocity);
  87569. };
  87570. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87571. var v = impostor.physicsBody.linearVelocity;
  87572. if (!v) {
  87573. return null;
  87574. }
  87575. return new BABYLON.Vector3(v.x, v.y, v.z);
  87576. };
  87577. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87578. var v = impostor.physicsBody.angularVelocity;
  87579. if (!v) {
  87580. return null;
  87581. }
  87582. return new BABYLON.Vector3(v.x, v.y, v.z);
  87583. };
  87584. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87585. var staticBody = mass === 0;
  87586. //this will actually set the body's density and not its mass.
  87587. //But this is how oimo treats the mass variable.
  87588. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87589. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87590. };
  87591. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87592. return impostor.physicsBody.shapes.density;
  87593. };
  87594. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87595. return impostor.physicsBody.shapes.friction;
  87596. };
  87597. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87598. impostor.physicsBody.shapes.friction = friction;
  87599. };
  87600. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87601. return impostor.physicsBody.shapes.restitution;
  87602. };
  87603. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87604. impostor.physicsBody.shapes.restitution = restitution;
  87605. };
  87606. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87607. impostor.physicsBody.sleep();
  87608. };
  87609. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87610. impostor.physicsBody.awake();
  87611. };
  87612. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87613. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87614. if (minDistance !== void 0) {
  87615. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87616. }
  87617. };
  87618. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87619. //TODO separate rotational and transational motors.
  87620. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87621. if (motor) {
  87622. motor.setMotor(speed, maxForce);
  87623. }
  87624. };
  87625. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87626. //TODO separate rotational and transational motors.
  87627. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87628. if (motor) {
  87629. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87630. }
  87631. };
  87632. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87633. var body = impostor.physicsBody;
  87634. mesh.position.x = body.position.x;
  87635. mesh.position.y = body.position.y;
  87636. mesh.position.z = body.position.z;
  87637. if (mesh.rotationQuaternion) {
  87638. mesh.rotationQuaternion.x = body.orientation.x;
  87639. mesh.rotationQuaternion.y = body.orientation.y;
  87640. mesh.rotationQuaternion.z = body.orientation.z;
  87641. mesh.rotationQuaternion.w = body.orientation.s;
  87642. }
  87643. };
  87644. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87645. return impostor.physicsBody.shapes.radius;
  87646. };
  87647. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87648. var shape = impostor.physicsBody.shapes;
  87649. result.x = shape.halfWidth * 2;
  87650. result.y = shape.halfHeight * 2;
  87651. result.z = shape.halfDepth * 2;
  87652. };
  87653. OimoJSPlugin.prototype.dispose = function () {
  87654. this.world.clear();
  87655. };
  87656. return OimoJSPlugin;
  87657. }());
  87658. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87659. })(BABYLON || (BABYLON = {}));
  87660. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87661. var BABYLON;
  87662. (function (BABYLON) {
  87663. /*
  87664. * Based on jsTGALoader - Javascript loader for TGA file
  87665. * By Vincent Thibault
  87666. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87667. */
  87668. var TGATools = /** @class */ (function () {
  87669. function TGATools() {
  87670. }
  87671. TGATools.GetTGAHeader = function (data) {
  87672. var offset = 0;
  87673. var header = {
  87674. id_length: data[offset++],
  87675. colormap_type: data[offset++],
  87676. image_type: data[offset++],
  87677. colormap_index: data[offset++] | data[offset++] << 8,
  87678. colormap_length: data[offset++] | data[offset++] << 8,
  87679. colormap_size: data[offset++],
  87680. origin: [
  87681. data[offset++] | data[offset++] << 8,
  87682. data[offset++] | data[offset++] << 8
  87683. ],
  87684. width: data[offset++] | data[offset++] << 8,
  87685. height: data[offset++] | data[offset++] << 8,
  87686. pixel_size: data[offset++],
  87687. flags: data[offset++]
  87688. };
  87689. return header;
  87690. };
  87691. /**
  87692. * Uploads TGA content to a Babylon Texture
  87693. * @hidden
  87694. */
  87695. TGATools.UploadContent = function (texture, data) {
  87696. // Not enough data to contain header ?
  87697. if (data.length < 19) {
  87698. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87699. return;
  87700. }
  87701. // Read Header
  87702. var offset = 18;
  87703. var header = TGATools.GetTGAHeader(data);
  87704. // Assume it's a valid Targa file.
  87705. if (header.id_length + offset > data.length) {
  87706. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87707. return;
  87708. }
  87709. // Skip not needed data
  87710. offset += header.id_length;
  87711. var use_rle = false;
  87712. var use_pal = false;
  87713. var use_grey = false;
  87714. // Get some informations.
  87715. switch (header.image_type) {
  87716. case TGATools._TYPE_RLE_INDEXED:
  87717. use_rle = true;
  87718. case TGATools._TYPE_INDEXED:
  87719. use_pal = true;
  87720. break;
  87721. case TGATools._TYPE_RLE_RGB:
  87722. use_rle = true;
  87723. case TGATools._TYPE_RGB:
  87724. // use_rgb = true;
  87725. break;
  87726. case TGATools._TYPE_RLE_GREY:
  87727. use_rle = true;
  87728. case TGATools._TYPE_GREY:
  87729. use_grey = true;
  87730. break;
  87731. }
  87732. var pixel_data;
  87733. // var numAlphaBits = header.flags & 0xf;
  87734. var pixel_size = header.pixel_size >> 3;
  87735. var pixel_total = header.width * header.height * pixel_size;
  87736. // Read palettes
  87737. var palettes;
  87738. if (use_pal) {
  87739. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87740. }
  87741. // Read LRE
  87742. if (use_rle) {
  87743. pixel_data = new Uint8Array(pixel_total);
  87744. var c, count, i;
  87745. var localOffset = 0;
  87746. var pixels = new Uint8Array(pixel_size);
  87747. while (offset < pixel_total && localOffset < pixel_total) {
  87748. c = data[offset++];
  87749. count = (c & 0x7f) + 1;
  87750. // RLE pixels
  87751. if (c & 0x80) {
  87752. // Bind pixel tmp array
  87753. for (i = 0; i < pixel_size; ++i) {
  87754. pixels[i] = data[offset++];
  87755. }
  87756. // Copy pixel array
  87757. for (i = 0; i < count; ++i) {
  87758. pixel_data.set(pixels, localOffset + i * pixel_size);
  87759. }
  87760. localOffset += pixel_size * count;
  87761. }
  87762. // Raw pixels
  87763. else {
  87764. count *= pixel_size;
  87765. for (i = 0; i < count; ++i) {
  87766. pixel_data[localOffset + i] = data[offset++];
  87767. }
  87768. localOffset += count;
  87769. }
  87770. }
  87771. }
  87772. // RAW Pixels
  87773. else {
  87774. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87775. }
  87776. // Load to texture
  87777. var x_start, y_start, x_step, y_step, y_end, x_end;
  87778. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87779. default:
  87780. case TGATools._ORIGIN_UL:
  87781. x_start = 0;
  87782. x_step = 1;
  87783. x_end = header.width;
  87784. y_start = 0;
  87785. y_step = 1;
  87786. y_end = header.height;
  87787. break;
  87788. case TGATools._ORIGIN_BL:
  87789. x_start = 0;
  87790. x_step = 1;
  87791. x_end = header.width;
  87792. y_start = header.height - 1;
  87793. y_step = -1;
  87794. y_end = -1;
  87795. break;
  87796. case TGATools._ORIGIN_UR:
  87797. x_start = header.width - 1;
  87798. x_step = -1;
  87799. x_end = -1;
  87800. y_start = 0;
  87801. y_step = 1;
  87802. y_end = header.height;
  87803. break;
  87804. case TGATools._ORIGIN_BR:
  87805. x_start = header.width - 1;
  87806. x_step = -1;
  87807. x_end = -1;
  87808. y_start = header.height - 1;
  87809. y_step = -1;
  87810. y_end = -1;
  87811. break;
  87812. }
  87813. // Load the specify method
  87814. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87815. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87816. var engine = texture.getEngine();
  87817. engine._uploadDataToTextureDirectly(texture, imageData);
  87818. };
  87819. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87820. var image = pixel_data, colormap = palettes;
  87821. var width = header.width, height = header.height;
  87822. var color, i = 0, x, y;
  87823. var imageData = new Uint8Array(width * height * 4);
  87824. for (y = y_start; y !== y_end; y += y_step) {
  87825. for (x = x_start; x !== x_end; x += x_step, i++) {
  87826. color = image[i];
  87827. imageData[(x + width * y) * 4 + 3] = 255;
  87828. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87829. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87830. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87831. }
  87832. }
  87833. return imageData;
  87834. };
  87835. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87836. var image = pixel_data;
  87837. var width = header.width, height = header.height;
  87838. var color, i = 0, x, y;
  87839. var imageData = new Uint8Array(width * height * 4);
  87840. for (y = y_start; y !== y_end; y += y_step) {
  87841. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87842. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87843. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87844. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87845. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87846. imageData[(x + width * y) * 4 + 0] = r;
  87847. imageData[(x + width * y) * 4 + 1] = g;
  87848. imageData[(x + width * y) * 4 + 2] = b;
  87849. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  87850. }
  87851. }
  87852. return imageData;
  87853. };
  87854. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87855. var image = pixel_data;
  87856. var width = header.width, height = header.height;
  87857. var i = 0, x, y;
  87858. var imageData = new Uint8Array(width * height * 4);
  87859. for (y = y_start; y !== y_end; y += y_step) {
  87860. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  87861. imageData[(x + width * y) * 4 + 3] = 255;
  87862. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87863. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87864. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87865. }
  87866. }
  87867. return imageData;
  87868. };
  87869. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87870. var image = pixel_data;
  87871. var width = header.width, height = header.height;
  87872. var i = 0, x, y;
  87873. var imageData = new Uint8Array(width * height * 4);
  87874. for (y = y_start; y !== y_end; y += y_step) {
  87875. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87876. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87877. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87878. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87879. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87880. }
  87881. }
  87882. return imageData;
  87883. };
  87884. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87885. var image = pixel_data;
  87886. var width = header.width, height = header.height;
  87887. var color, i = 0, x, y;
  87888. var imageData = new Uint8Array(width * height * 4);
  87889. for (y = y_start; y !== y_end; y += y_step) {
  87890. for (x = x_start; x !== x_end; x += x_step, i++) {
  87891. color = image[i];
  87892. imageData[(x + width * y) * 4 + 0] = color;
  87893. imageData[(x + width * y) * 4 + 1] = color;
  87894. imageData[(x + width * y) * 4 + 2] = color;
  87895. imageData[(x + width * y) * 4 + 3] = 255;
  87896. }
  87897. }
  87898. return imageData;
  87899. };
  87900. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87901. var image = pixel_data;
  87902. var width = header.width, height = header.height;
  87903. var i = 0, x, y;
  87904. var imageData = new Uint8Array(width * height * 4);
  87905. for (y = y_start; y !== y_end; y += y_step) {
  87906. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87907. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87908. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87909. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87910. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87911. }
  87912. }
  87913. return imageData;
  87914. };
  87915. //private static _TYPE_NO_DATA = 0;
  87916. TGATools._TYPE_INDEXED = 1;
  87917. TGATools._TYPE_RGB = 2;
  87918. TGATools._TYPE_GREY = 3;
  87919. TGATools._TYPE_RLE_INDEXED = 9;
  87920. TGATools._TYPE_RLE_RGB = 10;
  87921. TGATools._TYPE_RLE_GREY = 11;
  87922. TGATools._ORIGIN_MASK = 0x30;
  87923. TGATools._ORIGIN_SHIFT = 0x04;
  87924. TGATools._ORIGIN_BL = 0x00;
  87925. TGATools._ORIGIN_BR = 0x01;
  87926. TGATools._ORIGIN_UL = 0x02;
  87927. TGATools._ORIGIN_UR = 0x03;
  87928. return TGATools;
  87929. }());
  87930. BABYLON.TGATools = TGATools;
  87931. })(BABYLON || (BABYLON = {}));
  87932. //# sourceMappingURL=babylon.tga.js.map
  87933. var BABYLON;
  87934. (function (BABYLON) {
  87935. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87936. // All values and structures referenced from:
  87937. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87938. var DDS_MAGIC = 0x20534444;
  87939. var
  87940. //DDSD_CAPS = 0x1,
  87941. //DDSD_HEIGHT = 0x2,
  87942. //DDSD_WIDTH = 0x4,
  87943. //DDSD_PITCH = 0x8,
  87944. //DDSD_PIXELFORMAT = 0x1000,
  87945. DDSD_MIPMAPCOUNT = 0x20000;
  87946. //DDSD_LINEARSIZE = 0x80000,
  87947. //DDSD_DEPTH = 0x800000;
  87948. // var DDSCAPS_COMPLEX = 0x8,
  87949. // DDSCAPS_MIPMAP = 0x400000,
  87950. // DDSCAPS_TEXTURE = 0x1000;
  87951. var DDSCAPS2_CUBEMAP = 0x200;
  87952. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87953. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87954. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87955. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87956. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87957. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87958. // DDSCAPS2_VOLUME = 0x200000;
  87959. var
  87960. //DDPF_ALPHAPIXELS = 0x1,
  87961. //DDPF_ALPHA = 0x2,
  87962. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87963. //DDPF_YUV = 0x200,
  87964. DDPF_LUMINANCE = 0x20000;
  87965. function FourCCToInt32(value) {
  87966. return value.charCodeAt(0) +
  87967. (value.charCodeAt(1) << 8) +
  87968. (value.charCodeAt(2) << 16) +
  87969. (value.charCodeAt(3) << 24);
  87970. }
  87971. function Int32ToFourCC(value) {
  87972. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87973. }
  87974. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87975. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87976. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87977. var FOURCC_DX10 = FourCCToInt32("DX10");
  87978. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87979. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87980. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87981. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87982. var headerLengthInt = 31; // The header length in 32 bit ints
  87983. // Offsets into the header array
  87984. var off_magic = 0;
  87985. var off_size = 1;
  87986. var off_flags = 2;
  87987. var off_height = 3;
  87988. var off_width = 4;
  87989. var off_mipmapCount = 7;
  87990. var off_pfFlags = 20;
  87991. var off_pfFourCC = 21;
  87992. var off_RGBbpp = 22;
  87993. var off_RMask = 23;
  87994. var off_GMask = 24;
  87995. var off_BMask = 25;
  87996. var off_AMask = 26;
  87997. // var off_caps1 = 27;
  87998. var off_caps2 = 28;
  87999. // var off_caps3 = 29;
  88000. // var off_caps4 = 30;
  88001. var off_dxgiFormat = 32;
  88002. ;
  88003. var DDSTools = /** @class */ (function () {
  88004. function DDSTools() {
  88005. }
  88006. DDSTools.GetDDSInfo = function (arrayBuffer) {
  88007. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88008. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  88009. var mipmapCount = 1;
  88010. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  88011. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88012. }
  88013. var fourCC = header[off_pfFourCC];
  88014. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  88015. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88016. switch (fourCC) {
  88017. case FOURCC_D3DFMT_R16G16B16A16F:
  88018. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88019. break;
  88020. case FOURCC_D3DFMT_R32G32B32A32F:
  88021. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88022. break;
  88023. case FOURCC_DX10:
  88024. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  88025. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88026. break;
  88027. }
  88028. }
  88029. return {
  88030. width: header[off_width],
  88031. height: header[off_height],
  88032. mipmapCount: mipmapCount,
  88033. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  88034. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  88035. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  88036. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  88037. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  88038. dxgiFormat: dxgiFormat,
  88039. textureType: textureType
  88040. };
  88041. };
  88042. DDSTools._ToHalfFloat = function (value) {
  88043. if (!DDSTools._FloatView) {
  88044. DDSTools._FloatView = new Float32Array(1);
  88045. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  88046. }
  88047. DDSTools._FloatView[0] = value;
  88048. var x = DDSTools._Int32View[0];
  88049. var bits = (x >> 16) & 0x8000; /* Get the sign */
  88050. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  88051. var e = (x >> 23) & 0xff; /* Using int is faster here */
  88052. /* If zero, or denormal, or exponent underflows too much for a denormal
  88053. * half, return signed zero. */
  88054. if (e < 103) {
  88055. return bits;
  88056. }
  88057. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  88058. if (e > 142) {
  88059. bits |= 0x7c00;
  88060. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  88061. * not Inf, so make sure we set one mantissa bit too. */
  88062. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  88063. return bits;
  88064. }
  88065. /* If exponent underflows but not too much, return a denormal */
  88066. if (e < 113) {
  88067. m |= 0x0800;
  88068. /* Extra rounding may overflow and set mantissa to 0 and exponent
  88069. * to 1, which is OK. */
  88070. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  88071. return bits;
  88072. }
  88073. bits |= ((e - 112) << 10) | (m >> 1);
  88074. bits += m & 1;
  88075. return bits;
  88076. };
  88077. DDSTools._FromHalfFloat = function (value) {
  88078. var s = (value & 0x8000) >> 15;
  88079. var e = (value & 0x7C00) >> 10;
  88080. var f = value & 0x03FF;
  88081. if (e === 0) {
  88082. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  88083. }
  88084. else if (e == 0x1F) {
  88085. return f ? NaN : ((s ? -1 : 1) * Infinity);
  88086. }
  88087. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  88088. };
  88089. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88090. var destArray = new Float32Array(dataLength);
  88091. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88092. var index = 0;
  88093. for (var y = 0; y < height; y++) {
  88094. for (var x = 0; x < width; x++) {
  88095. var srcPos = (x + y * width) * 4;
  88096. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  88097. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  88098. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  88099. if (DDSTools.StoreLODInAlphaChannel) {
  88100. destArray[index + 3] = lod;
  88101. }
  88102. else {
  88103. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  88104. }
  88105. index += 4;
  88106. }
  88107. }
  88108. return destArray;
  88109. };
  88110. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88111. if (DDSTools.StoreLODInAlphaChannel) {
  88112. var destArray = new Uint16Array(dataLength);
  88113. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88114. var index = 0;
  88115. for (var y = 0; y < height; y++) {
  88116. for (var x = 0; x < width; x++) {
  88117. var srcPos = (x + y * width) * 4;
  88118. destArray[index] = srcData[srcPos];
  88119. destArray[index + 1] = srcData[srcPos + 1];
  88120. destArray[index + 2] = srcData[srcPos + 2];
  88121. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  88122. index += 4;
  88123. }
  88124. }
  88125. return destArray;
  88126. }
  88127. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  88128. };
  88129. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88130. if (DDSTools.StoreLODInAlphaChannel) {
  88131. var destArray = new Float32Array(dataLength);
  88132. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88133. var index = 0;
  88134. for (var y = 0; y < height; y++) {
  88135. for (var x = 0; x < width; x++) {
  88136. var srcPos = (x + y * width) * 4;
  88137. destArray[index] = srcData[srcPos];
  88138. destArray[index + 1] = srcData[srcPos + 1];
  88139. destArray[index + 2] = srcData[srcPos + 2];
  88140. destArray[index + 3] = lod;
  88141. index += 4;
  88142. }
  88143. }
  88144. return destArray;
  88145. }
  88146. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  88147. };
  88148. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88149. var destArray = new Uint8Array(dataLength);
  88150. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88151. var index = 0;
  88152. for (var y = 0; y < height; y++) {
  88153. for (var x = 0; x < width; x++) {
  88154. var srcPos = (x + y * width) * 4;
  88155. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  88156. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  88157. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  88158. if (DDSTools.StoreLODInAlphaChannel) {
  88159. destArray[index + 3] = lod;
  88160. }
  88161. else {
  88162. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  88163. }
  88164. index += 4;
  88165. }
  88166. }
  88167. return destArray;
  88168. };
  88169. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88170. var destArray = new Uint8Array(dataLength);
  88171. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88172. var index = 0;
  88173. for (var y = 0; y < height; y++) {
  88174. for (var x = 0; x < width; x++) {
  88175. var srcPos = (x + y * width) * 4;
  88176. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  88177. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  88178. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  88179. if (DDSTools.StoreLODInAlphaChannel) {
  88180. destArray[index + 3] = lod;
  88181. }
  88182. else {
  88183. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  88184. }
  88185. index += 4;
  88186. }
  88187. }
  88188. return destArray;
  88189. };
  88190. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  88191. var byteArray = new Uint8Array(dataLength);
  88192. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88193. var index = 0;
  88194. for (var y = 0; y < height; y++) {
  88195. for (var x = 0; x < width; x++) {
  88196. var srcPos = (x + y * width) * 4;
  88197. byteArray[index] = srcData[srcPos + rOffset];
  88198. byteArray[index + 1] = srcData[srcPos + gOffset];
  88199. byteArray[index + 2] = srcData[srcPos + bOffset];
  88200. byteArray[index + 3] = srcData[srcPos + aOffset];
  88201. index += 4;
  88202. }
  88203. }
  88204. return byteArray;
  88205. };
  88206. DDSTools._ExtractLongWordOrder = function (value) {
  88207. if (value === 0 || value === 255 || value === -16777216) {
  88208. return 0;
  88209. }
  88210. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  88211. };
  88212. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  88213. var byteArray = new Uint8Array(dataLength);
  88214. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88215. var index = 0;
  88216. for (var y = 0; y < height; y++) {
  88217. for (var x = 0; x < width; x++) {
  88218. var srcPos = (x + y * width) * 3;
  88219. byteArray[index] = srcData[srcPos + rOffset];
  88220. byteArray[index + 1] = srcData[srcPos + gOffset];
  88221. byteArray[index + 2] = srcData[srcPos + bOffset];
  88222. index += 3;
  88223. }
  88224. }
  88225. return byteArray;
  88226. };
  88227. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  88228. var byteArray = new Uint8Array(dataLength);
  88229. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88230. var index = 0;
  88231. for (var y = 0; y < height; y++) {
  88232. for (var x = 0; x < width; x++) {
  88233. var srcPos = (x + y * width);
  88234. byteArray[index] = srcData[srcPos];
  88235. index++;
  88236. }
  88237. }
  88238. return byteArray;
  88239. };
  88240. /**
  88241. * Uploads DDS Levels to a Babylon Texture
  88242. * @hidden
  88243. */
  88244. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  88245. if (lodIndex === void 0) { lodIndex = -1; }
  88246. var sphericalPolynomialFaces = null;
  88247. if (info.sphericalPolynomial) {
  88248. sphericalPolynomialFaces = new Array();
  88249. }
  88250. var ext = engine.getCaps().s3tc;
  88251. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88252. var fourCC, width, height, dataLength = 0, dataOffset;
  88253. var byteArray, mipmapCount, mip;
  88254. var internalCompressedFormat = 0;
  88255. var blockBytes = 1;
  88256. if (header[off_magic] !== DDS_MAGIC) {
  88257. BABYLON.Tools.Error("Invalid magic number in DDS header");
  88258. return;
  88259. }
  88260. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  88261. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  88262. return;
  88263. }
  88264. if (info.isCompressed && !ext) {
  88265. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  88266. return;
  88267. }
  88268. var bpp = header[off_RGBbpp];
  88269. dataOffset = header[off_size] + 4;
  88270. var computeFormats = false;
  88271. if (info.isFourCC) {
  88272. fourCC = header[off_pfFourCC];
  88273. switch (fourCC) {
  88274. case FOURCC_DXT1:
  88275. blockBytes = 8;
  88276. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  88277. break;
  88278. case FOURCC_DXT3:
  88279. blockBytes = 16;
  88280. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  88281. break;
  88282. case FOURCC_DXT5:
  88283. blockBytes = 16;
  88284. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  88285. break;
  88286. case FOURCC_D3DFMT_R16G16B16A16F:
  88287. computeFormats = true;
  88288. break;
  88289. case FOURCC_D3DFMT_R32G32B32A32F:
  88290. computeFormats = true;
  88291. break;
  88292. case FOURCC_DX10:
  88293. // There is an additionnal header so dataOffset need to be changed
  88294. dataOffset += 5 * 4; // 5 uints
  88295. var supported = false;
  88296. switch (info.dxgiFormat) {
  88297. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  88298. computeFormats = true;
  88299. supported = true;
  88300. break;
  88301. case DXGI_FORMAT_B8G8R8X8_UNORM:
  88302. info.isRGB = true;
  88303. info.isFourCC = false;
  88304. bpp = 32;
  88305. supported = true;
  88306. break;
  88307. }
  88308. if (supported) {
  88309. break;
  88310. }
  88311. default:
  88312. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  88313. return;
  88314. }
  88315. }
  88316. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  88317. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  88318. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  88319. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  88320. if (computeFormats) {
  88321. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  88322. }
  88323. mipmapCount = 1;
  88324. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  88325. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88326. }
  88327. for (var face = 0; face < faces; face++) {
  88328. width = header[off_width];
  88329. height = header[off_height];
  88330. for (mip = 0; mip < mipmapCount; ++mip) {
  88331. if (lodIndex === -1 || lodIndex === mip) {
  88332. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  88333. var i = (lodIndex === -1) ? mip : 0;
  88334. if (!info.isCompressed && info.isFourCC) {
  88335. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88336. dataLength = width * height * 4;
  88337. var floatArray = null;
  88338. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  88339. if (bpp === 128) {
  88340. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88341. if (sphericalPolynomialFaces && i == 0) {
  88342. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88343. }
  88344. }
  88345. else if (bpp === 64) {
  88346. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88347. if (sphericalPolynomialFaces && i == 0) {
  88348. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88349. }
  88350. }
  88351. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88352. }
  88353. else {
  88354. if (bpp === 128) {
  88355. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88356. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88357. if (sphericalPolynomialFaces && i == 0) {
  88358. sphericalPolynomialFaces.push(floatArray);
  88359. }
  88360. }
  88361. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  88362. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88363. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88364. if (sphericalPolynomialFaces && i == 0) {
  88365. sphericalPolynomialFaces.push(floatArray);
  88366. }
  88367. }
  88368. else { // 64
  88369. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88370. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88371. if (sphericalPolynomialFaces && i == 0) {
  88372. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88373. }
  88374. }
  88375. }
  88376. if (floatArray) {
  88377. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  88378. }
  88379. }
  88380. else if (info.isRGB) {
  88381. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88382. if (bpp === 24) {
  88383. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  88384. dataLength = width * height * 3;
  88385. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  88386. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88387. }
  88388. else { // 32
  88389. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88390. dataLength = width * height * 4;
  88391. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  88392. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88393. }
  88394. }
  88395. else if (info.isLuminance) {
  88396. var unpackAlignment = engine._getUnpackAlignement();
  88397. var unpaddedRowSize = width;
  88398. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  88399. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  88400. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  88401. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  88402. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88403. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88404. }
  88405. else {
  88406. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  88407. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  88408. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88409. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  88410. }
  88411. }
  88412. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  88413. width *= 0.5;
  88414. height *= 0.5;
  88415. width = Math.max(1.0, width);
  88416. height = Math.max(1.0, height);
  88417. }
  88418. if (currentFace !== undefined) {
  88419. // Loading a single face
  88420. break;
  88421. }
  88422. }
  88423. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  88424. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  88425. size: header[off_width],
  88426. right: sphericalPolynomialFaces[0],
  88427. left: sphericalPolynomialFaces[1],
  88428. up: sphericalPolynomialFaces[2],
  88429. down: sphericalPolynomialFaces[3],
  88430. front: sphericalPolynomialFaces[4],
  88431. back: sphericalPolynomialFaces[5],
  88432. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  88433. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88434. gammaSpace: false,
  88435. });
  88436. }
  88437. else {
  88438. info.sphericalPolynomial = undefined;
  88439. }
  88440. };
  88441. DDSTools.StoreLODInAlphaChannel = false;
  88442. return DDSTools;
  88443. }());
  88444. BABYLON.DDSTools = DDSTools;
  88445. })(BABYLON || (BABYLON = {}));
  88446. //# sourceMappingURL=babylon.dds.js.map
  88447. var BABYLON;
  88448. (function (BABYLON) {
  88449. /**
  88450. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88451. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88452. */
  88453. var KhronosTextureContainer = /** @class */ (function () {
  88454. /**
  88455. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88456. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88457. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88458. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88459. */
  88460. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88461. this.arrayBuffer = arrayBuffer;
  88462. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88463. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88464. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88465. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88466. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88467. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88468. BABYLON.Tools.Error("texture missing KTX identifier");
  88469. return;
  88470. }
  88471. // load the reset of the header in native 32 bit int
  88472. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88473. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88474. var oppositeEndianess = header[0] === 0x01020304;
  88475. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88476. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88477. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88478. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88479. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88480. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88481. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88482. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88483. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88484. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88485. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88486. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88487. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88488. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88489. if (this.glType !== 0) {
  88490. BABYLON.Tools.Error("only compressed formats currently supported");
  88491. return;
  88492. }
  88493. else {
  88494. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88495. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88496. }
  88497. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88498. BABYLON.Tools.Error("only 2D textures currently supported");
  88499. return;
  88500. }
  88501. if (this.numberOfArrayElements !== 0) {
  88502. BABYLON.Tools.Error("texture arrays not currently supported");
  88503. return;
  88504. }
  88505. if (this.numberOfFaces !== facesExpected) {
  88506. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88507. return;
  88508. }
  88509. // we now have a completely validated file, so could use existence of loadType as success
  88510. // would need to make this more elaborate & adjust checks above to support more than one load type
  88511. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88512. }
  88513. // not as fast hardware based, but will probably never need to use
  88514. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88515. return ((val & 0xFF) << 24)
  88516. | ((val & 0xFF00) << 8)
  88517. | ((val >> 8) & 0xFF00)
  88518. | ((val >> 24) & 0xFF);
  88519. };
  88520. /**
  88521. * Uploads KTX content to a Babylon Texture.
  88522. * It is assumed that the texture has already been created & is currently bound
  88523. * @hidden
  88524. */
  88525. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88526. switch (this.loadType) {
  88527. case KhronosTextureContainer.COMPRESSED_2D:
  88528. this._upload2DCompressedLevels(texture, loadMipmaps);
  88529. break;
  88530. case KhronosTextureContainer.TEX_2D:
  88531. case KhronosTextureContainer.COMPRESSED_3D:
  88532. case KhronosTextureContainer.TEX_3D:
  88533. }
  88534. };
  88535. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88536. // initialize width & height for level 1
  88537. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88538. var width = this.pixelWidth;
  88539. var height = this.pixelHeight;
  88540. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88541. for (var level = 0; level < mipmapCount; level++) {
  88542. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88543. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88544. for (var face = 0; face < this.numberOfFaces; face++) {
  88545. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88546. var engine = texture.getEngine();
  88547. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88548. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88549. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88550. }
  88551. width = Math.max(1.0, width * 0.5);
  88552. height = Math.max(1.0, height * 0.5);
  88553. }
  88554. };
  88555. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88556. // load types
  88557. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88558. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88559. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88560. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88561. return KhronosTextureContainer;
  88562. }());
  88563. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88564. })(BABYLON || (BABYLON = {}));
  88565. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88566. var BABYLON;
  88567. (function (BABYLON) {
  88568. /**
  88569. * Renders a layer on top of an existing scene
  88570. */
  88571. var UtilityLayerRenderer = /** @class */ (function () {
  88572. /**
  88573. * Instantiates a UtilityLayerRenderer
  88574. * @param originalScene the original scene that will be rendered on top of
  88575. */
  88576. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88577. var _this = this;
  88578. this.originalScene = originalScene;
  88579. this._pointerCaptures = {};
  88580. this._lastPointerEvents = {};
  88581. /**
  88582. * If the utility layer should automatically be rendered on top of existing scene
  88583. */
  88584. this.shouldRender = true;
  88585. /**
  88586. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88587. */
  88588. this.onlyCheckPointerDownEvents = true;
  88589. /**
  88590. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88591. */
  88592. this.processAllEvents = false;
  88593. /**
  88594. * Observable raised when the pointer move from the utility layer scene to the main scene
  88595. */
  88596. this.onPointerOutObservable = new BABYLON.Observable();
  88597. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88598. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88599. this.utilityLayerScene._allowPostProcessClear = false;
  88600. originalScene.getEngine().scenes.pop();
  88601. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88602. this.utilityLayerScene.detachControl();
  88603. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88604. if (!_this.processAllEvents) {
  88605. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88606. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88607. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88608. return;
  88609. }
  88610. }
  88611. var pointerEvent = (prePointerInfo.event);
  88612. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88613. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88614. return;
  88615. }
  88616. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88617. if (!prePointerInfo.ray && utilityScenePick) {
  88618. prePointerInfo.ray = utilityScenePick.ray;
  88619. }
  88620. // always fire the prepointer oversvable
  88621. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88622. // allow every non pointer down event to flow to the utility layer
  88623. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88624. if (!prePointerInfo.skipOnPointerObservable) {
  88625. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88626. }
  88627. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88628. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88629. }
  88630. return;
  88631. }
  88632. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88633. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88634. if (utilityScenePick && utilityScenePick.hit) {
  88635. if (!prePointerInfo.skipOnPointerObservable) {
  88636. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88637. }
  88638. prePointerInfo.skipOnPointerObservable = true;
  88639. }
  88640. }
  88641. else {
  88642. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88643. var pointerEvent_1 = (prePointerInfo.event);
  88644. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88645. if (originalScenePick && utilityScenePick) {
  88646. // No pick in utility scene
  88647. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88648. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88649. // We touched an utility mesh present in the main scene
  88650. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88651. prePointerInfo.skipOnPointerObservable = true;
  88652. }
  88653. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88654. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88655. }
  88656. }
  88657. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88658. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88659. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88660. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88661. }
  88662. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88663. // We have a pick in both scenes but main is closer than utility
  88664. // We touched an utility mesh present in the main scene
  88665. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88666. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88667. prePointerInfo.skipOnPointerObservable = true;
  88668. }
  88669. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88670. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88671. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88672. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88673. }
  88674. }
  88675. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88676. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88677. }
  88678. }
  88679. }
  88680. });
  88681. // Render directly on top of existing scene without clearing
  88682. this.utilityLayerScene.autoClear = false;
  88683. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88684. if (_this.shouldRender) {
  88685. _this.render();
  88686. }
  88687. });
  88688. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88689. _this.dispose();
  88690. });
  88691. this._updateCamera();
  88692. }
  88693. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88694. get: function () {
  88695. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88696. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88697. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88698. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88699. });
  88700. }
  88701. return UtilityLayerRenderer._DefaultUtilityLayer;
  88702. },
  88703. enumerable: true,
  88704. configurable: true
  88705. });
  88706. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88707. if (!prePointerInfo.skipOnPointerObservable) {
  88708. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88709. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88710. }
  88711. };
  88712. /**
  88713. * Renders the utility layers scene on top of the original scene
  88714. */
  88715. UtilityLayerRenderer.prototype.render = function () {
  88716. this._updateCamera();
  88717. if (this.utilityLayerScene.activeCamera) {
  88718. // Set the camera's scene to utility layers scene
  88719. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  88720. var camera = this.utilityLayerScene.activeCamera;
  88721. camera._scene = this.utilityLayerScene;
  88722. if (camera.leftCamera) {
  88723. camera.leftCamera._scene = this.utilityLayerScene;
  88724. }
  88725. if (camera.rightCamera) {
  88726. camera.rightCamera._scene = this.utilityLayerScene;
  88727. }
  88728. this.utilityLayerScene.render(false);
  88729. // Reset camera's scene back to original
  88730. camera._scene = oldScene;
  88731. if (camera.leftCamera) {
  88732. camera.leftCamera._scene = oldScene;
  88733. }
  88734. if (camera.rightCamera) {
  88735. camera.rightCamera._scene = oldScene;
  88736. }
  88737. }
  88738. };
  88739. /**
  88740. * Disposes of the renderer
  88741. */
  88742. UtilityLayerRenderer.prototype.dispose = function () {
  88743. this.onPointerOutObservable.clear();
  88744. if (this._afterRenderObserver) {
  88745. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88746. }
  88747. if (this._sceneDisposeObserver) {
  88748. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88749. }
  88750. if (this._originalPointerObserver) {
  88751. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88752. }
  88753. this.utilityLayerScene.dispose();
  88754. };
  88755. UtilityLayerRenderer.prototype._updateCamera = function () {
  88756. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88757. };
  88758. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88759. return UtilityLayerRenderer;
  88760. }());
  88761. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88762. })(BABYLON || (BABYLON = {}));
  88763. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88764. //# sourceMappingURL=babylon.behavior.js.map
  88765. var BABYLON;
  88766. (function (BABYLON) {
  88767. /**
  88768. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88769. */
  88770. var PointerDragBehavior = /** @class */ (function () {
  88771. /**
  88772. * Creates a pointer drag behavior that can be attached to a mesh
  88773. * @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)
  88774. */
  88775. function PointerDragBehavior(options) {
  88776. /**
  88777. * 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)
  88778. */
  88779. this.maxDragAngle = 0;
  88780. /**
  88781. * @hidden
  88782. */
  88783. this._useAlternatePickedPointAboveMaxDragAngle = false;
  88784. /**
  88785. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88786. */
  88787. this.currentDraggingPointerID = -1;
  88788. /**
  88789. * If the behavior is currently in a dragging state
  88790. */
  88791. this.dragging = false;
  88792. /**
  88793. * 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)
  88794. */
  88795. this.dragDeltaRatio = 0.2;
  88796. /**
  88797. * If the drag plane orientation should be updated during the dragging (Default: true)
  88798. */
  88799. this.updateDragPlane = true;
  88800. // Debug mode will display drag planes to help visualize behavior
  88801. this._debugMode = false;
  88802. this._moving = false;
  88803. /**
  88804. * Fires each time the attached mesh is dragged with the pointer
  88805. * * delta between last drag position and current drag position in world space
  88806. * * dragDistance along the drag axis
  88807. * * dragPlaneNormal normal of the current drag plane used during the drag
  88808. * * dragPlanePoint in world space where the drag intersects the drag plane
  88809. */
  88810. this.onDragObservable = new BABYLON.Observable();
  88811. /**
  88812. * Fires each time a drag begins (eg. mouse down on mesh)
  88813. */
  88814. this.onDragStartObservable = new BABYLON.Observable();
  88815. /**
  88816. * Fires each time a drag ends (eg. mouse release after drag)
  88817. */
  88818. this.onDragEndObservable = new BABYLON.Observable();
  88819. /**
  88820. * If the attached mesh should be moved when dragged
  88821. */
  88822. this.moveAttached = true;
  88823. /**
  88824. * If the drag behavior will react to drag events (Default: true)
  88825. */
  88826. this.enabled = true;
  88827. /**
  88828. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88829. */
  88830. this.useObjectOrienationForDragging = true;
  88831. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88832. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  88833. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88834. // Variables to avoid instantiation in the below method
  88835. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88836. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88837. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88838. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88839. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88840. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88841. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88842. this._options = options ? options : {};
  88843. var optionCount = 0;
  88844. if (this._options.dragAxis) {
  88845. optionCount++;
  88846. }
  88847. if (this._options.dragPlaneNormal) {
  88848. optionCount++;
  88849. }
  88850. if (optionCount > 1) {
  88851. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88852. }
  88853. }
  88854. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88855. /**
  88856. * The name of the behavior
  88857. */
  88858. get: function () {
  88859. return "PointerDrag";
  88860. },
  88861. enumerable: true,
  88862. configurable: true
  88863. });
  88864. /**
  88865. * Initializes the behavior
  88866. */
  88867. PointerDragBehavior.prototype.init = function () { };
  88868. /**
  88869. * Attaches the drag behavior the passed in mesh
  88870. * @param ownerNode The mesh that will be dragged around once attached
  88871. */
  88872. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88873. var _this = this;
  88874. this._scene = ownerNode.getScene();
  88875. this._attachedNode = ownerNode;
  88876. // Initialize drag plane to not interfere with existing scene
  88877. if (!PointerDragBehavior._planeScene) {
  88878. if (this._debugMode) {
  88879. PointerDragBehavior._planeScene = this._scene;
  88880. }
  88881. else {
  88882. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88883. PointerDragBehavior._planeScene.detachControl();
  88884. this._scene.getEngine().scenes.pop();
  88885. }
  88886. }
  88887. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88888. // State of the drag
  88889. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88890. var delta = new BABYLON.Vector3(0, 0, 0);
  88891. var dragLength = 0;
  88892. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88893. var pickPredicate = function (m) {
  88894. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88895. };
  88896. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88897. if (!_this.enabled) {
  88898. return;
  88899. }
  88900. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88901. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88902. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88903. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88904. if (pickedPoint) {
  88905. _this.dragging = true;
  88906. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88907. _this.lastDragPosition.copyFrom(pickedPoint);
  88908. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88909. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88910. }
  88911. }
  88912. }
  88913. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88914. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88915. _this.releaseDrag();
  88916. }
  88917. }
  88918. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88919. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88920. _this._moving = true;
  88921. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88922. if (pickedPoint) {
  88923. if (_this.updateDragPlane) {
  88924. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88925. }
  88926. // depending on the drag mode option drag accordingly
  88927. if (_this._options.dragAxis) {
  88928. // Convert local drag axis to world
  88929. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88930. // Project delta drag from the drag plane onto the drag axis
  88931. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88932. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88933. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88934. }
  88935. else {
  88936. dragLength = delta.length();
  88937. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88938. }
  88939. targetPosition.addInPlace(delta);
  88940. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88941. _this.lastDragPosition.copyFrom(pickedPoint);
  88942. }
  88943. }
  88944. }
  88945. });
  88946. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  88947. if (_this._moving && _this.moveAttached) {
  88948. // Slowly move mesh to avoid jitter
  88949. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88950. _this._tmpVector.scaleInPlace(0.2);
  88951. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88952. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88953. }
  88954. });
  88955. };
  88956. PointerDragBehavior.prototype.releaseDrag = function () {
  88957. this.dragging = false;
  88958. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88959. this.currentDraggingPointerID = -1;
  88960. this._moving = false;
  88961. };
  88962. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88963. var _this = this;
  88964. if (!ray) {
  88965. return null;
  88966. }
  88967. // Calculate angle between plane normal and ray
  88968. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  88969. // Correct if ray is casted from oposite side
  88970. if (angle > Math.PI / 2) {
  88971. angle = Math.PI - angle;
  88972. }
  88973. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  88974. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  88975. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  88976. // Invert ray direction along the towards object axis
  88977. this._tmpVector.copyFrom(ray.direction);
  88978. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  88979. this._alternatePickedPoint.normalize();
  88980. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  88981. this._tmpVector.addInPlace(this._alternatePickedPoint);
  88982. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  88983. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  88984. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  88985. this._alternatePickedPoint.addInPlace(this._tmpVector);
  88986. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  88987. return this._alternatePickedPoint;
  88988. }
  88989. else {
  88990. return null;
  88991. }
  88992. }
  88993. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88994. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88995. return pickResult.pickedPoint;
  88996. }
  88997. else {
  88998. return null;
  88999. }
  89000. };
  89001. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89002. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89003. this._pointA.copyFrom(dragPlanePosition);
  89004. if (this._options.dragAxis) {
  89005. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89006. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89007. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89008. ray.origin.subtractToRef(this._pointA, this._pointC);
  89009. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89010. // Get perpendicular line from direction to camera and drag axis
  89011. this._pointB.subtractToRef(this._pointA, this._lineA);
  89012. this._pointC.subtractToRef(this._pointA, this._lineB);
  89013. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89014. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89015. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89016. this._lookAt.normalize();
  89017. this._dragPlane.position.copyFrom(this._pointA);
  89018. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89019. this._dragPlane.lookAt(this._lookAt);
  89020. }
  89021. else if (this._options.dragPlaneNormal) {
  89022. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89023. this._dragPlane.position.copyFrom(this._pointA);
  89024. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89025. this._dragPlane.lookAt(this._lookAt);
  89026. }
  89027. else {
  89028. this._dragPlane.position.copyFrom(this._pointA);
  89029. this._dragPlane.lookAt(ray.origin);
  89030. }
  89031. this._dragPlane.computeWorldMatrix(true);
  89032. };
  89033. /**
  89034. * Detaches the behavior from the mesh
  89035. */
  89036. PointerDragBehavior.prototype.detach = function () {
  89037. if (this._pointerObserver) {
  89038. this._scene.onPointerObservable.remove(this._pointerObserver);
  89039. }
  89040. if (this._beforeRenderObserver) {
  89041. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89042. }
  89043. };
  89044. return PointerDragBehavior;
  89045. }());
  89046. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89047. })(BABYLON || (BABYLON = {}));
  89048. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89049. var BABYLON;
  89050. (function (BABYLON) {
  89051. /**
  89052. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89053. */
  89054. var MultiPointerScaleBehavior = /** @class */ (function () {
  89055. function MultiPointerScaleBehavior() {
  89056. this._startDistance = 0;
  89057. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89058. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89059. this._sceneRenderObserver = null;
  89060. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89061. this._dragBehaviorA.moveAttached = false;
  89062. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89063. this._dragBehaviorB.moveAttached = false;
  89064. }
  89065. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89066. /**
  89067. * The name of the behavior
  89068. */
  89069. get: function () {
  89070. return "MultiPointerScale";
  89071. },
  89072. enumerable: true,
  89073. configurable: true
  89074. });
  89075. /**
  89076. * Initializes the behavior
  89077. */
  89078. MultiPointerScaleBehavior.prototype.init = function () { };
  89079. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89080. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89081. };
  89082. /**
  89083. * Attaches the scale behavior the passed in mesh
  89084. * @param ownerNode The mesh that will be scaled around once attached
  89085. */
  89086. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89087. var _this = this;
  89088. this._ownerNode = ownerNode;
  89089. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89090. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89091. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89092. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89093. _this._dragBehaviorA.releaseDrag();
  89094. }
  89095. else {
  89096. _this._initialScale.copyFrom(ownerNode.scaling);
  89097. _this._startDistance = _this._getCurrentDistance();
  89098. }
  89099. }
  89100. });
  89101. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89102. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89103. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89104. _this._dragBehaviorB.releaseDrag();
  89105. }
  89106. else {
  89107. _this._initialScale.copyFrom(ownerNode.scaling);
  89108. _this._startDistance = _this._getCurrentDistance();
  89109. }
  89110. }
  89111. });
  89112. // Once both drag behaviors are active scale based on the distance between the two pointers
  89113. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89114. behavior.onDragObservable.add(function () {
  89115. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89116. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89117. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89118. }
  89119. });
  89120. });
  89121. ownerNode.addBehavior(this._dragBehaviorA);
  89122. ownerNode.addBehavior(this._dragBehaviorB);
  89123. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89124. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89125. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89126. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89127. if (change.length() > 0.01) {
  89128. ownerNode.scaling.addInPlace(change);
  89129. }
  89130. }
  89131. });
  89132. };
  89133. /**
  89134. * Detaches the behavior from the mesh
  89135. */
  89136. MultiPointerScaleBehavior.prototype.detach = function () {
  89137. var _this = this;
  89138. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89139. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89140. behavior.onDragStartObservable.clear();
  89141. behavior.onDragObservable.clear();
  89142. _this._ownerNode.removeBehavior(behavior);
  89143. });
  89144. };
  89145. return MultiPointerScaleBehavior;
  89146. }());
  89147. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89148. })(BABYLON || (BABYLON = {}));
  89149. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89150. var BABYLON;
  89151. (function (BABYLON) {
  89152. /**
  89153. * 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
  89154. */
  89155. var SixDofDragBehavior = /** @class */ (function () {
  89156. function SixDofDragBehavior() {
  89157. this._sceneRenderObserver = null;
  89158. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89159. this._moving = false;
  89160. this._startingOrientation = new BABYLON.Quaternion();
  89161. /**
  89162. * 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)
  89163. */
  89164. this.zDragFactor = 3;
  89165. /**
  89166. * If the behavior is currently in a dragging state
  89167. */
  89168. this.dragging = false;
  89169. /**
  89170. * 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)
  89171. */
  89172. this.dragDeltaRatio = 0.2;
  89173. /**
  89174. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89175. */
  89176. this.currentDraggingPointerID = -1;
  89177. }
  89178. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89179. /**
  89180. * The name of the behavior
  89181. */
  89182. get: function () {
  89183. return "SixDofDrag";
  89184. },
  89185. enumerable: true,
  89186. configurable: true
  89187. });
  89188. /**
  89189. * Initializes the behavior
  89190. */
  89191. SixDofDragBehavior.prototype.init = function () { };
  89192. /**
  89193. * Attaches the scale behavior the passed in mesh
  89194. * @param ownerNode The mesh that will be scaled around once attached
  89195. */
  89196. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89197. var _this = this;
  89198. this._ownerNode = ownerNode;
  89199. this._scene = this._ownerNode.getScene();
  89200. if (!SixDofDragBehavior._virtualScene) {
  89201. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89202. this._scene.getEngine().scenes.pop();
  89203. }
  89204. var pickedMesh = null;
  89205. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89206. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89207. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89208. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89209. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89210. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89211. var pickPredicate = function (m) {
  89212. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89213. };
  89214. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89215. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89216. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89217. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89218. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89219. }
  89220. pickedMesh = _this._ownerNode;
  89221. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89222. // Set position and orientation of the controller
  89223. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89224. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89225. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89226. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89227. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89228. if (!pickedMesh.rotationQuaternion) {
  89229. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89230. }
  89231. var oldParent = pickedMesh.parent;
  89232. pickedMesh.setParent(null);
  89233. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89234. pickedMesh.setParent(oldParent);
  89235. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89236. // Update state
  89237. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89238. _this.dragging = true;
  89239. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89240. }
  89241. }
  89242. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89243. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89244. _this.dragging = false;
  89245. _this._moving = false;
  89246. _this.currentDraggingPointerID = -1;
  89247. pickedMesh = null;
  89248. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89249. }
  89250. }
  89251. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89252. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89253. var zDragFactor = _this.zDragFactor;
  89254. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89255. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89256. zDragFactor = 0;
  89257. }
  89258. // Calculate controller drag distance in controller space
  89259. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89260. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89261. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89262. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89263. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89264. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89265. if (_this._virtualDragMesh.position.z < 0) {
  89266. _this._virtualDragMesh.position.z = 0;
  89267. }
  89268. // Update the controller position
  89269. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89270. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89271. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89272. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89273. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89274. if (pickedMesh.parent) {
  89275. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89276. }
  89277. if (!_this._moving) {
  89278. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89279. }
  89280. _this._moving = true;
  89281. }
  89282. }
  89283. });
  89284. var tmpQuaternion = new BABYLON.Quaternion();
  89285. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89286. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89287. if (_this.dragging && _this._moving && pickedMesh) {
  89288. // Slowly move mesh to avoid jitter
  89289. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89290. // Get change in rotation
  89291. tmpQuaternion.copyFrom(_this._startingOrientation);
  89292. tmpQuaternion.x = -tmpQuaternion.x;
  89293. tmpQuaternion.y = -tmpQuaternion.y;
  89294. tmpQuaternion.z = -tmpQuaternion.z;
  89295. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89296. // Convert change in rotation to only y axis rotation
  89297. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89298. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89299. // Slowly move mesh to avoid jitter
  89300. var oldParent = pickedMesh.parent;
  89301. pickedMesh.setParent(null);
  89302. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89303. pickedMesh.setParent(oldParent);
  89304. }
  89305. });
  89306. };
  89307. /**
  89308. * Detaches the behavior from the mesh
  89309. */
  89310. SixDofDragBehavior.prototype.detach = function () {
  89311. if (this._scene) {
  89312. this._scene.onPointerObservable.remove(this._pointerObserver);
  89313. }
  89314. if (this._ownerNode) {
  89315. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89316. }
  89317. if (this._virtualOriginMesh) {
  89318. this._virtualOriginMesh.dispose();
  89319. }
  89320. if (this._virtualDragMesh) {
  89321. this._virtualDragMesh.dispose();
  89322. }
  89323. };
  89324. return SixDofDragBehavior;
  89325. }());
  89326. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89327. })(BABYLON || (BABYLON = {}));
  89328. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89329. var BABYLON;
  89330. (function (BABYLON) {
  89331. /**
  89332. * @hidden
  89333. */
  89334. var FaceDirectionInfo = /** @class */ (function () {
  89335. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  89336. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  89337. if (diff === void 0) { diff = 0; }
  89338. if (ignore === void 0) { ignore = false; }
  89339. this.direction = direction;
  89340. this.rotatedDirection = rotatedDirection;
  89341. this.diff = diff;
  89342. this.ignore = ignore;
  89343. }
  89344. return FaceDirectionInfo;
  89345. }());
  89346. /**
  89347. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  89348. */
  89349. var AttachToBoxBehavior = /** @class */ (function () {
  89350. /**
  89351. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  89352. * @param ui The transform node that should be attched to the mesh
  89353. */
  89354. function AttachToBoxBehavior(ui) {
  89355. this.ui = ui;
  89356. /**
  89357. * The name of the behavior
  89358. */
  89359. this.name = "AttachToBoxBehavior";
  89360. /**
  89361. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  89362. */
  89363. this.distanceAwayFromFace = 0.15;
  89364. /**
  89365. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  89366. */
  89367. this.distanceAwayFromBottomOfFace = 0.15;
  89368. 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))];
  89369. this._tmpMatrix = new BABYLON.Matrix();
  89370. this._tmpVector = new BABYLON.Vector3();
  89371. this._zeroVector = BABYLON.Vector3.Zero();
  89372. this._lookAtTmpMatrix = new BABYLON.Matrix();
  89373. /* Does nothing */
  89374. }
  89375. /**
  89376. * Initializes the behavior
  89377. */
  89378. AttachToBoxBehavior.prototype.init = function () {
  89379. /* Does nothing */
  89380. };
  89381. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  89382. var _this = this;
  89383. // Go over each face and calculate the angle between the face's normal and targetDirection
  89384. this._faceVectors.forEach(function (v) {
  89385. if (!_this._target.rotationQuaternion) {
  89386. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  89387. }
  89388. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  89389. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  89390. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  89391. });
  89392. // Return the face information of the one with the normal closeset to target direction
  89393. return this._faceVectors.reduce(function (min, p) {
  89394. if (min.ignore) {
  89395. return p;
  89396. }
  89397. else if (p.ignore) {
  89398. return min;
  89399. }
  89400. else {
  89401. return min.diff < p.diff ? min : p;
  89402. }
  89403. }, this._faceVectors[0]);
  89404. };
  89405. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  89406. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  89407. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  89408. this._lookAtTmpMatrix.invert();
  89409. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  89410. };
  89411. /**
  89412. * Attaches the AttachToBoxBehavior to the passed in mesh
  89413. * @param target The mesh that the specified node will be attached to
  89414. */
  89415. AttachToBoxBehavior.prototype.attach = function (target) {
  89416. var _this = this;
  89417. this._target = target;
  89418. this._scene = this._target.getScene();
  89419. // Every frame, update the app bars position
  89420. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89421. if (!_this._scene.activeCamera) {
  89422. return;
  89423. }
  89424. // Find the face closest to the cameras position
  89425. var cameraPos = _this._scene.activeCamera.position;
  89426. if (_this._scene.activeCamera.devicePosition) {
  89427. cameraPos = _this._scene.activeCamera.devicePosition;
  89428. }
  89429. var facing = _this._closestFace(cameraPos.subtract(target.position));
  89430. if (_this._scene.activeCamera.leftCamera) {
  89431. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89432. }
  89433. else {
  89434. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89435. }
  89436. // Get camera up direction
  89437. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  89438. // Ignore faces to not select a parrelel face for the up vector of the UI
  89439. _this._faceVectors.forEach(function (v) {
  89440. if (facing.direction.x && v.direction.x) {
  89441. v.ignore = true;
  89442. }
  89443. if (facing.direction.y && v.direction.y) {
  89444. v.ignore = true;
  89445. }
  89446. if (facing.direction.z && v.direction.z) {
  89447. v.ignore = true;
  89448. }
  89449. });
  89450. var facingUp = _this._closestFace(_this._tmpVector);
  89451. // Unignore faces
  89452. _this._faceVectors.forEach(function (v) {
  89453. v.ignore = false;
  89454. });
  89455. // Position the app bar on that face
  89456. _this.ui.position.copyFrom(target.position);
  89457. if (facing.direction.x) {
  89458. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89459. _this.ui.position.addInPlace(_this._tmpVector);
  89460. }
  89461. if (facing.direction.y) {
  89462. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89463. _this.ui.position.addInPlace(_this._tmpVector);
  89464. }
  89465. if (facing.direction.z) {
  89466. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89467. _this.ui.position.addInPlace(_this._tmpVector);
  89468. }
  89469. // Rotate to be oriented properly to the camera
  89470. if (!_this.ui.rotationQuaternion) {
  89471. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  89472. }
  89473. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  89474. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  89475. // Place ui the correct distance from the bottom of the mesh
  89476. if (facingUp.direction.x) {
  89477. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  89478. }
  89479. if (facingUp.direction.y) {
  89480. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  89481. }
  89482. if (facingUp.direction.z) {
  89483. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  89484. }
  89485. _this.ui.position.addInPlace(_this._tmpVector);
  89486. });
  89487. };
  89488. /**
  89489. * Detaches the behavior from the mesh
  89490. */
  89491. AttachToBoxBehavior.prototype.detach = function () {
  89492. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  89493. };
  89494. return AttachToBoxBehavior;
  89495. }());
  89496. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  89497. })(BABYLON || (BABYLON = {}));
  89498. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  89499. var BABYLON;
  89500. (function (BABYLON) {
  89501. /**
  89502. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89503. */
  89504. var Gizmo = /** @class */ (function () {
  89505. /**
  89506. * Creates a gizmo
  89507. * @param gizmoLayer The utility layer the gizmo will be added to
  89508. */
  89509. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89510. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89511. var _this = this;
  89512. this.gizmoLayer = gizmoLayer;
  89513. this._scaleFactor = 3;
  89514. this._tmpMatrix = new BABYLON.Matrix();
  89515. /**
  89516. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89517. */
  89518. this.updateGizmoRotationToMatchAttachedMesh = true;
  89519. /**
  89520. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89521. */
  89522. this.updateGizmoPositionToMatchAttachedMesh = true;
  89523. /**
  89524. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89525. */
  89526. this._updateScale = true;
  89527. this._interactionsEnabled = true;
  89528. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89529. var tempVector = new BABYLON.Vector3();
  89530. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89531. if (_this.attachedMesh) {
  89532. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89533. if (!_this._rootMesh.rotationQuaternion) {
  89534. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89535. }
  89536. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89537. tempVector.copyFrom(_this.attachedMesh.scaling);
  89538. if (_this.attachedMesh.scaling.x < 0) {
  89539. _this.attachedMesh.scaling.x *= -1;
  89540. }
  89541. if (_this.attachedMesh.scaling.y < 0) {
  89542. _this.attachedMesh.scaling.y *= -1;
  89543. }
  89544. if (_this.attachedMesh.scaling.z < 0) {
  89545. _this.attachedMesh.scaling.z *= -1;
  89546. }
  89547. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89548. _this.attachedMesh.scaling.copyFrom(tempVector);
  89549. _this.attachedMesh.computeWorldMatrix();
  89550. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89551. }
  89552. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89553. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89554. }
  89555. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89556. var cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.position;
  89557. if (_this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  89558. cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  89559. }
  89560. _this._rootMesh.position.subtractToRef(cameraPosition, tempVector);
  89561. var dist = tempVector.length() / _this._scaleFactor;
  89562. _this._rootMesh.scaling.set(dist, dist, dist);
  89563. }
  89564. }
  89565. });
  89566. this.attachedMesh = null;
  89567. }
  89568. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89569. /**
  89570. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89571. * * When set, interactions will be enabled
  89572. */
  89573. get: function () {
  89574. return this._attachedMesh;
  89575. },
  89576. set: function (value) {
  89577. this._attachedMesh = value;
  89578. this._rootMesh.setEnabled(value ? true : false);
  89579. this._attachedMeshChanged(value);
  89580. },
  89581. enumerable: true,
  89582. configurable: true
  89583. });
  89584. Gizmo.prototype._attachedMeshChanged = function (value) {
  89585. };
  89586. /**
  89587. * Disposes of the gizmo
  89588. */
  89589. Gizmo.prototype.dispose = function () {
  89590. this._rootMesh.dispose();
  89591. if (this._beforeRenderObserver) {
  89592. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89593. }
  89594. };
  89595. return Gizmo;
  89596. }());
  89597. BABYLON.Gizmo = Gizmo;
  89598. })(BABYLON || (BABYLON = {}));
  89599. //# sourceMappingURL=babylon.gizmo.js.map
  89600. var BABYLON;
  89601. (function (BABYLON) {
  89602. /**
  89603. * Single axis drag gizmo
  89604. */
  89605. var AxisDragGizmo = /** @class */ (function (_super) {
  89606. __extends(AxisDragGizmo, _super);
  89607. /**
  89608. * Creates an AxisDragGizmo
  89609. * @param gizmoLayer The utility layer the gizmo will be added to
  89610. * @param dragAxis The axis which the gizmo will be able to drag on
  89611. * @param color The color of the gizmo
  89612. */
  89613. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89614. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89615. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89616. var _this = _super.call(this, gizmoLayer) || this;
  89617. _this._pointerObserver = null;
  89618. /**
  89619. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89620. */
  89621. _this.snapDistance = 0;
  89622. /**
  89623. * Event that fires each time the gizmo snaps to a new location.
  89624. * * snapDistance is the the change in distance
  89625. */
  89626. _this.onSnapObservable = new BABYLON.Observable();
  89627. // Create Material
  89628. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89629. coloredMaterial.disableLighting = true;
  89630. coloredMaterial.emissiveColor = color;
  89631. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89632. hoverMaterial.disableLighting = true;
  89633. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89634. // Build mesh on root node
  89635. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89636. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89637. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89638. arrow.addChild(arrowMesh);
  89639. arrow.addChild(arrowTail);
  89640. // Position arrow pointing in its drag axis
  89641. arrowMesh.scaling.scaleInPlace(0.05);
  89642. arrowMesh.material = coloredMaterial;
  89643. arrowMesh.rotation.x = Math.PI / 2;
  89644. arrowMesh.position.z += 0.3;
  89645. arrowTail.rotation.x = Math.PI / 2;
  89646. arrowTail.material = coloredMaterial;
  89647. arrowTail.position.z += 0.15;
  89648. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89649. _this._rootMesh.addChild(arrow);
  89650. var currentSnapDragDistance = 0;
  89651. var tmpVector = new BABYLON.Vector3();
  89652. var tmpSnapEvent = { snapDistance: 0 };
  89653. // Add drag behavior to handle events when the gizmo is dragged
  89654. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89655. _this.dragBehavior.moveAttached = false;
  89656. _this._rootMesh.addBehavior(_this.dragBehavior);
  89657. _this.dragBehavior.onDragObservable.add(function (event) {
  89658. if (_this.attachedMesh) {
  89659. // Snapping logic
  89660. if (_this.snapDistance == 0) {
  89661. _this.attachedMesh.position.addInPlace(event.delta);
  89662. }
  89663. else {
  89664. currentSnapDragDistance += event.dragDistance;
  89665. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89666. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89667. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89668. event.delta.normalizeToRef(tmpVector);
  89669. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89670. _this.attachedMesh.position.addInPlace(tmpVector);
  89671. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89672. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89673. }
  89674. }
  89675. }
  89676. });
  89677. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89678. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89679. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89680. m.material = hoverMaterial;
  89681. });
  89682. }
  89683. else {
  89684. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89685. m.material = coloredMaterial;
  89686. });
  89687. }
  89688. });
  89689. return _this;
  89690. }
  89691. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89692. if (this.dragBehavior) {
  89693. this.dragBehavior.enabled = value ? true : false;
  89694. }
  89695. };
  89696. /**
  89697. * Disposes of the gizmo
  89698. */
  89699. AxisDragGizmo.prototype.dispose = function () {
  89700. this.onSnapObservable.clear();
  89701. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89702. this.dragBehavior.detach();
  89703. _super.prototype.dispose.call(this);
  89704. };
  89705. return AxisDragGizmo;
  89706. }(BABYLON.Gizmo));
  89707. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89708. })(BABYLON || (BABYLON = {}));
  89709. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89710. var BABYLON;
  89711. (function (BABYLON) {
  89712. /**
  89713. * Single axis scale gizmo
  89714. */
  89715. var AxisScaleGizmo = /** @class */ (function (_super) {
  89716. __extends(AxisScaleGizmo, _super);
  89717. /**
  89718. * Creates an AxisScaleGizmo
  89719. * @param gizmoLayer The utility layer the gizmo will be added to
  89720. * @param dragAxis The axis which the gizmo will be able to scale on
  89721. * @param color The color of the gizmo
  89722. */
  89723. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89724. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89725. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89726. var _this = _super.call(this, gizmoLayer) || this;
  89727. _this._pointerObserver = null;
  89728. /**
  89729. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89730. */
  89731. _this.snapDistance = 0;
  89732. /**
  89733. * Event that fires each time the gizmo snaps to a new location.
  89734. * * snapDistance is the the change in distance
  89735. */
  89736. _this.onSnapObservable = new BABYLON.Observable();
  89737. // Create Material
  89738. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89739. coloredMaterial.disableLighting = true;
  89740. coloredMaterial.emissiveColor = color;
  89741. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89742. hoverMaterial.disableLighting = true;
  89743. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89744. // Build mesh on root node
  89745. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89746. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89747. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89748. arrow.addChild(arrowMesh);
  89749. arrow.addChild(arrowTail);
  89750. // Position arrow pointing in its drag axis
  89751. arrowMesh.scaling.scaleInPlace(0.1);
  89752. arrowMesh.material = coloredMaterial;
  89753. arrowMesh.rotation.x = Math.PI / 2;
  89754. arrowMesh.position.z += 0.3;
  89755. arrowTail.rotation.x = Math.PI / 2;
  89756. arrowTail.material = coloredMaterial;
  89757. arrowTail.position.z += 0.15;
  89758. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89759. _this._rootMesh.addChild(arrow);
  89760. // Add drag behavior to handle events when the gizmo is dragged
  89761. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89762. _this.dragBehavior.moveAttached = false;
  89763. _this._rootMesh.addBehavior(_this.dragBehavior);
  89764. var currentSnapDragDistance = 0;
  89765. var tmpVector = new BABYLON.Vector3();
  89766. var tmpSnapEvent = { snapDistance: 0 };
  89767. _this.dragBehavior.onDragObservable.add(function (event) {
  89768. if (_this.attachedMesh) {
  89769. // Snapping logic
  89770. var snapped = false;
  89771. var dragSteps = 0;
  89772. if (_this.snapDistance == 0) {
  89773. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89774. }
  89775. else {
  89776. currentSnapDragDistance += event.dragDistance;
  89777. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89778. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89779. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89780. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89781. snapped = true;
  89782. }
  89783. else {
  89784. tmpVector.scaleInPlace(0);
  89785. }
  89786. }
  89787. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89788. if (snapped) {
  89789. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89790. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89791. }
  89792. }
  89793. });
  89794. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89795. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89796. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89797. m.material = hoverMaterial;
  89798. });
  89799. }
  89800. else {
  89801. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89802. m.material = coloredMaterial;
  89803. });
  89804. }
  89805. });
  89806. return _this;
  89807. }
  89808. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89809. if (this.dragBehavior) {
  89810. this.dragBehavior.enabled = value ? true : false;
  89811. }
  89812. };
  89813. /**
  89814. * Disposes of the gizmo
  89815. */
  89816. AxisScaleGizmo.prototype.dispose = function () {
  89817. this.onSnapObservable.clear();
  89818. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89819. this.dragBehavior.detach();
  89820. _super.prototype.dispose.call(this);
  89821. };
  89822. return AxisScaleGizmo;
  89823. }(BABYLON.Gizmo));
  89824. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89825. })(BABYLON || (BABYLON = {}));
  89826. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89827. var BABYLON;
  89828. (function (BABYLON) {
  89829. /**
  89830. * Single plane rotation gizmo
  89831. */
  89832. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89833. __extends(PlaneRotationGizmo, _super);
  89834. /**
  89835. * Creates a PlaneRotationGizmo
  89836. * @param gizmoLayer The utility layer the gizmo will be added to
  89837. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89838. * @param color The color of the gizmo
  89839. */
  89840. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89841. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89842. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89843. var _this = _super.call(this, gizmoLayer) || this;
  89844. _this._pointerObserver = null;
  89845. /**
  89846. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89847. */
  89848. _this.snapDistance = 0;
  89849. /**
  89850. * Event that fires each time the gizmo snaps to a new location.
  89851. * * snapDistance is the the change in distance
  89852. */
  89853. _this.onSnapObservable = new BABYLON.Observable();
  89854. // Create Material
  89855. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89856. coloredMaterial.disableLighting = true;
  89857. coloredMaterial.emissiveColor = color;
  89858. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89859. hoverMaterial.disableLighting = true;
  89860. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89861. // Build mesh on root node
  89862. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89863. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89864. // Position arrow pointing in its drag axis
  89865. rotationMesh.scaling.scaleInPlace(0.1);
  89866. rotationMesh.material = coloredMaterial;
  89867. rotationMesh.rotation.x = Math.PI / 2;
  89868. parentMesh.addChild(rotationMesh);
  89869. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89870. _this._rootMesh.addChild(parentMesh);
  89871. // Add drag behavior to handle events when the gizmo is dragged
  89872. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89873. _this.dragBehavior.moveAttached = false;
  89874. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  89875. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  89876. _this._rootMesh.addBehavior(_this.dragBehavior);
  89877. var lastDragPosition = new BABYLON.Vector3();
  89878. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89879. if (_this.attachedMesh) {
  89880. lastDragPosition.copyFrom(e.dragPlanePoint);
  89881. }
  89882. });
  89883. var rotationMatrix = new BABYLON.Matrix();
  89884. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89885. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89886. var tmpSnapEvent = { snapDistance: 0 };
  89887. var currentSnapDragDistance = 0;
  89888. _this.dragBehavior.onDragObservable.add(function (event) {
  89889. if (_this.attachedMesh) {
  89890. if (!_this.attachedMesh.rotationQuaternion) {
  89891. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89892. }
  89893. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89894. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89895. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89896. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89897. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89898. var angle = Math.atan2(cross.length(), dot);
  89899. planeNormalTowardsCamera.copyFrom(planeNormal);
  89900. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89901. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89902. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89903. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89904. }
  89905. // Flip up vector depending on which side the camera is on
  89906. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89907. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89908. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89909. planeNormalTowardsCamera.scaleInPlace(-1);
  89910. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89911. }
  89912. }
  89913. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89914. if (halfCircleSide)
  89915. angle = -angle;
  89916. // Snapping logic
  89917. var snapped = false;
  89918. if (_this.snapDistance != 0) {
  89919. currentSnapDragDistance += angle;
  89920. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89921. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89922. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89923. angle = _this.snapDistance * dragSteps;
  89924. snapped = true;
  89925. }
  89926. else {
  89927. angle = 0;
  89928. }
  89929. }
  89930. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89931. var quaternionCoefficient = Math.sin(angle / 2);
  89932. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89933. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89934. // Rotate selected mesh quaternion over fixed axis
  89935. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89936. }
  89937. else {
  89938. // Rotate selected mesh quaternion over rotated axis
  89939. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  89940. }
  89941. lastDragPosition.copyFrom(event.dragPlanePoint);
  89942. if (snapped) {
  89943. tmpSnapEvent.snapDistance = angle;
  89944. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89945. }
  89946. }
  89947. });
  89948. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89949. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89950. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89951. m.material = hoverMaterial;
  89952. });
  89953. }
  89954. else {
  89955. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89956. m.material = coloredMaterial;
  89957. });
  89958. }
  89959. });
  89960. return _this;
  89961. }
  89962. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89963. if (this.dragBehavior) {
  89964. this.dragBehavior.enabled = value ? true : false;
  89965. }
  89966. };
  89967. /**
  89968. * Disposes of the gizmo
  89969. */
  89970. PlaneRotationGizmo.prototype.dispose = function () {
  89971. this.onSnapObservable.clear();
  89972. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89973. this.dragBehavior.detach();
  89974. _super.prototype.dispose.call(this);
  89975. };
  89976. return PlaneRotationGizmo;
  89977. }(BABYLON.Gizmo));
  89978. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89979. })(BABYLON || (BABYLON = {}));
  89980. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89981. var BABYLON;
  89982. (function (BABYLON) {
  89983. /**
  89984. * Gizmo that enables dragging a mesh along 3 axis
  89985. */
  89986. var PositionGizmo = /** @class */ (function (_super) {
  89987. __extends(PositionGizmo, _super);
  89988. /**
  89989. * Creates a PositionGizmo
  89990. * @param gizmoLayer The utility layer the gizmo will be added to
  89991. */
  89992. function PositionGizmo(gizmoLayer) {
  89993. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89994. var _this = _super.call(this, gizmoLayer) || this;
  89995. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89996. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89997. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89998. _this.attachedMesh = null;
  89999. return _this;
  90000. }
  90001. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90002. set: function (mesh) {
  90003. if (this.xGizmo) {
  90004. this.xGizmo.attachedMesh = mesh;
  90005. this.yGizmo.attachedMesh = mesh;
  90006. this.zGizmo.attachedMesh = mesh;
  90007. }
  90008. },
  90009. enumerable: true,
  90010. configurable: true
  90011. });
  90012. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90013. get: function () {
  90014. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90015. },
  90016. set: function (value) {
  90017. if (this.xGizmo) {
  90018. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90019. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90020. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90021. }
  90022. },
  90023. enumerable: true,
  90024. configurable: true
  90025. });
  90026. /**
  90027. * Disposes of the gizmo
  90028. */
  90029. PositionGizmo.prototype.dispose = function () {
  90030. this.xGizmo.dispose();
  90031. this.yGizmo.dispose();
  90032. this.zGizmo.dispose();
  90033. };
  90034. return PositionGizmo;
  90035. }(BABYLON.Gizmo));
  90036. BABYLON.PositionGizmo = PositionGizmo;
  90037. })(BABYLON || (BABYLON = {}));
  90038. //# sourceMappingURL=babylon.positionGizmo.js.map
  90039. var BABYLON;
  90040. (function (BABYLON) {
  90041. /**
  90042. * Gizmo that enables rotating a mesh along 3 axis
  90043. */
  90044. var RotationGizmo = /** @class */ (function (_super) {
  90045. __extends(RotationGizmo, _super);
  90046. /**
  90047. * Creates a RotationGizmo
  90048. * @param gizmoLayer The utility layer the gizmo will be added to
  90049. */
  90050. function RotationGizmo(gizmoLayer) {
  90051. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90052. var _this = _super.call(this, gizmoLayer) || this;
  90053. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90054. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90055. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90056. _this.attachedMesh = null;
  90057. return _this;
  90058. }
  90059. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90060. set: function (mesh) {
  90061. if (this.xGizmo) {
  90062. this.xGizmo.attachedMesh = mesh;
  90063. this.yGizmo.attachedMesh = mesh;
  90064. this.zGizmo.attachedMesh = mesh;
  90065. }
  90066. },
  90067. enumerable: true,
  90068. configurable: true
  90069. });
  90070. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90071. get: function () {
  90072. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90073. },
  90074. set: function (value) {
  90075. if (this.xGizmo) {
  90076. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90077. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90078. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90079. }
  90080. },
  90081. enumerable: true,
  90082. configurable: true
  90083. });
  90084. /**
  90085. * Disposes of the gizmo
  90086. */
  90087. RotationGizmo.prototype.dispose = function () {
  90088. this.xGizmo.dispose();
  90089. this.yGizmo.dispose();
  90090. this.zGizmo.dispose();
  90091. };
  90092. return RotationGizmo;
  90093. }(BABYLON.Gizmo));
  90094. BABYLON.RotationGizmo = RotationGizmo;
  90095. })(BABYLON || (BABYLON = {}));
  90096. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90097. var BABYLON;
  90098. (function (BABYLON) {
  90099. /**
  90100. * Gizmo that enables scaling a mesh along 3 axis
  90101. */
  90102. var ScaleGizmo = /** @class */ (function (_super) {
  90103. __extends(ScaleGizmo, _super);
  90104. /**
  90105. * Creates a ScaleGizmo
  90106. * @param gizmoLayer The utility layer the gizmo will be added to
  90107. */
  90108. function ScaleGizmo(gizmoLayer) {
  90109. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90110. var _this = _super.call(this, gizmoLayer) || this;
  90111. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90112. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90113. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90114. _this.attachedMesh = null;
  90115. return _this;
  90116. }
  90117. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90118. set: function (mesh) {
  90119. if (this.xGizmo) {
  90120. this.xGizmo.attachedMesh = mesh;
  90121. this.yGizmo.attachedMesh = mesh;
  90122. this.zGizmo.attachedMesh = mesh;
  90123. }
  90124. },
  90125. enumerable: true,
  90126. configurable: true
  90127. });
  90128. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90129. get: function () {
  90130. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90131. },
  90132. set: function (value) {
  90133. if (this.xGizmo) {
  90134. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90135. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90136. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90137. }
  90138. },
  90139. enumerable: true,
  90140. configurable: true
  90141. });
  90142. /**
  90143. * Disposes of the gizmo
  90144. */
  90145. ScaleGizmo.prototype.dispose = function () {
  90146. this.xGizmo.dispose();
  90147. this.yGizmo.dispose();
  90148. this.zGizmo.dispose();
  90149. };
  90150. return ScaleGizmo;
  90151. }(BABYLON.Gizmo));
  90152. BABYLON.ScaleGizmo = ScaleGizmo;
  90153. })(BABYLON || (BABYLON = {}));
  90154. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90155. var BABYLON;
  90156. (function (BABYLON) {
  90157. /**
  90158. * Bounding box gizmo
  90159. */
  90160. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90161. __extends(BoundingBoxGizmo, _super);
  90162. /**
  90163. * Creates an BoundingBoxGizmo
  90164. * @param gizmoLayer The utility layer the gizmo will be added to
  90165. * @param color The color of the gizmo
  90166. */
  90167. function BoundingBoxGizmo(color, gizmoLayer) {
  90168. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90169. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90170. var _this = _super.call(this, gizmoLayer) || this;
  90171. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90172. _this._renderObserver = null;
  90173. _this._pointerObserver = null;
  90174. _this._scaleDragSpeed = 0.2;
  90175. _this._tmpQuaternion = new BABYLON.Quaternion();
  90176. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90177. /**
  90178. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90179. */
  90180. _this.rotationSphereSize = 0.1;
  90181. /**
  90182. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90183. */
  90184. _this.scaleBoxSize = 0.1;
  90185. /**
  90186. * 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)
  90187. */
  90188. _this.fixedDragMeshScreenSize = false;
  90189. /**
  90190. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90191. */
  90192. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90193. /**
  90194. * Fired when a rotation sphere or scale box is dragged
  90195. */
  90196. _this.onDragStartObservable = new BABYLON.Observable();
  90197. /**
  90198. * Fired when a rotation sphere or scale box drag is started
  90199. */
  90200. _this.onDragObservable = new BABYLON.Observable();
  90201. /**
  90202. * Fired when a rotation sphere or scale box drag is needed
  90203. */
  90204. _this.onDragEndObservable = new BABYLON.Observable();
  90205. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90206. _this._updateScale = false;
  90207. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90208. // Create Materials
  90209. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90210. coloredMaterial.disableLighting = true;
  90211. coloredMaterial.emissiveColor = color;
  90212. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90213. hoverColoredMaterial.disableLighting = true;
  90214. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90215. // Build bounding box out of lines
  90216. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90217. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90218. var lines = [];
  90219. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90220. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90221. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90222. 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));
  90223. 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));
  90224. 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));
  90225. 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));
  90226. 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));
  90227. 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));
  90228. 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));
  90229. 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));
  90230. 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));
  90231. lines.forEach(function (l) {
  90232. l.color = color;
  90233. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90234. l.isPickable = false;
  90235. _this._lineBoundingBox.addChild(l);
  90236. });
  90237. _this._rootMesh.addChild(_this._lineBoundingBox);
  90238. // Create rotation spheres
  90239. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90240. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90241. var _loop_1 = function (i_1) {
  90242. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90243. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90244. sphere.material = coloredMaterial;
  90245. // Drag behavior
  90246. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90247. _dragBehavior.moveAttached = false;
  90248. _dragBehavior.updateDragPlane = false;
  90249. sphere.addBehavior(_dragBehavior);
  90250. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90251. var totalTurnAmountOfDrag = 0;
  90252. _dragBehavior.onDragStartObservable.add(function (event) {
  90253. startingTurnDirection.copyFrom(sphere.forward);
  90254. totalTurnAmountOfDrag = 0;
  90255. });
  90256. _dragBehavior.onDragObservable.add(function (event) {
  90257. _this.onDragObservable.notifyObservers({});
  90258. if (_this.attachedMesh) {
  90259. var worldDragDirection = startingTurnDirection;
  90260. // Project the world right on to the drag plane
  90261. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90262. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90263. // project drag delta on to the resulting drag axis and rotate based on that
  90264. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90265. // Rotate based on axis
  90266. if (!_this.attachedMesh.rotationQuaternion) {
  90267. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90268. }
  90269. if (!_this._anchorMesh.rotationQuaternion) {
  90270. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90271. }
  90272. // Do not allow the object to turn more than a full circle
  90273. totalTurnAmountOfDrag += projectDist;
  90274. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90275. if (i_1 >= 8) {
  90276. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90277. }
  90278. else if (i_1 >= 4) {
  90279. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90280. }
  90281. else {
  90282. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90283. }
  90284. // Rotate around center of bounding box
  90285. _this._anchorMesh.addChild(_this.attachedMesh);
  90286. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90287. _this._anchorMesh.removeChild(_this.attachedMesh);
  90288. }
  90289. }
  90290. });
  90291. // Selection/deselection
  90292. _dragBehavior.onDragStartObservable.add(function () {
  90293. _this.onDragStartObservable.notifyObservers({});
  90294. _this._selectNode(sphere);
  90295. });
  90296. _dragBehavior.onDragEndObservable.add(function () {
  90297. _this.onDragEndObservable.notifyObservers({});
  90298. _this._selectNode(null);
  90299. });
  90300. this_1._rotateSpheresParent.addChild(sphere);
  90301. };
  90302. var this_1 = this, _dragBehavior;
  90303. for (var i_1 = 0; i_1 < 12; i_1++) {
  90304. _loop_1(i_1);
  90305. }
  90306. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90307. // Create scale cubes
  90308. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90309. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90310. for (var i = 0; i < 2; i++) {
  90311. for (var j = 0; j < 2; j++) {
  90312. var _loop_2 = function () {
  90313. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90314. box.material = coloredMaterial;
  90315. // Dragging logic
  90316. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90317. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90318. _dragBehavior.moveAttached = false;
  90319. box.addBehavior(_dragBehavior);
  90320. _dragBehavior.onDragObservable.add(function (event) {
  90321. _this.onDragObservable.notifyObservers({});
  90322. if (_this.attachedMesh) {
  90323. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90324. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90325. _this._updateBoundingBox();
  90326. // Scale from the position of the opposite corner
  90327. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90328. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90329. _this._anchorMesh.addChild(_this.attachedMesh);
  90330. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90331. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90332. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90333. }
  90334. _this._anchorMesh.removeChild(_this.attachedMesh);
  90335. }
  90336. });
  90337. // Selection/deselection
  90338. _dragBehavior.onDragStartObservable.add(function () {
  90339. _this.onDragStartObservable.notifyObservers({});
  90340. _this._selectNode(box);
  90341. });
  90342. _dragBehavior.onDragEndObservable.add(function () {
  90343. _this.onDragEndObservable.notifyObservers({});
  90344. _this._selectNode(null);
  90345. });
  90346. this_2._scaleBoxesParent.addChild(box);
  90347. };
  90348. var this_2 = this, _dragBehavior;
  90349. for (var k = 0; k < 2; k++) {
  90350. _loop_2();
  90351. }
  90352. }
  90353. }
  90354. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90355. // Hover color change
  90356. var pointerIds = new Array();
  90357. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90358. if (!pointerIds[pointerInfo.event.pointerId]) {
  90359. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90360. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90361. pointerIds[pointerInfo.event.pointerId] = mesh;
  90362. mesh.material = hoverColoredMaterial;
  90363. }
  90364. });
  90365. }
  90366. else {
  90367. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90368. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90369. delete pointerIds[pointerInfo.event.pointerId];
  90370. }
  90371. }
  90372. });
  90373. // Update bounding box positions
  90374. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90375. _this._updateBoundingBox();
  90376. });
  90377. _this._updateBoundingBox();
  90378. return _this;
  90379. }
  90380. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90381. if (value) {
  90382. // Reset anchor mesh to match attached mesh's scale
  90383. // This is needed to avoid invalid box/sphere position on first drag
  90384. this._anchorMesh.addChild(value);
  90385. this._anchorMesh.removeChild(value);
  90386. this._updateBoundingBox();
  90387. }
  90388. };
  90389. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90390. this._rotateSpheresParent.getChildMeshes()
  90391. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90392. m.isVisible = (!selectedMesh || m == selectedMesh);
  90393. });
  90394. };
  90395. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90396. var _this = this;
  90397. mesh.computeWorldMatrix(true);
  90398. mesh.getChildMeshes().forEach(function (m) {
  90399. _this._recurseComputeWorld(m);
  90400. });
  90401. };
  90402. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90403. if (this.attachedMesh) {
  90404. // Rotate based on axis
  90405. if (!this.attachedMesh.rotationQuaternion) {
  90406. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90407. }
  90408. if (!this._anchorMesh.rotationQuaternion) {
  90409. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90410. }
  90411. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90412. // Store original position and reset mesh to origin before computing the bounding box
  90413. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90414. this._tmpVector.copyFrom(this.attachedMesh.position);
  90415. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90416. this.attachedMesh.position.set(0, 0, 0);
  90417. // Update bounding dimensions/positions
  90418. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90419. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90420. // Update gizmo to match bounding box scaling and rotation
  90421. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90422. 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);
  90423. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90424. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90425. this._lineBoundingBox.computeWorldMatrix();
  90426. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90427. // restore position/rotation values
  90428. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90429. this.attachedMesh.position.copyFrom(this._tmpVector);
  90430. this._recurseComputeWorld(this.attachedMesh);
  90431. }
  90432. // Update rotation sphere locations
  90433. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90434. for (var i = 0; i < 3; i++) {
  90435. for (var j = 0; j < 2; j++) {
  90436. for (var k = 0; k < 2; k++) {
  90437. var index = ((i * 4) + (j * 2)) + k;
  90438. if (i == 0) {
  90439. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90440. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90441. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90442. }
  90443. if (i == 1) {
  90444. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90445. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90446. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90447. }
  90448. if (i == 2) {
  90449. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90450. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90451. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90452. }
  90453. if (this.fixedDragMeshScreenSize) {
  90454. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90455. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90456. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90457. }
  90458. else {
  90459. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90460. }
  90461. }
  90462. }
  90463. }
  90464. // Update scale box locations
  90465. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90466. for (var i = 0; i < 2; i++) {
  90467. for (var j = 0; j < 2; j++) {
  90468. for (var k = 0; k < 2; k++) {
  90469. var index = ((i * 4) + (j * 2)) + k;
  90470. if (scaleBoxes[index]) {
  90471. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90472. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90473. if (this.fixedDragMeshScreenSize) {
  90474. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90475. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90476. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90477. }
  90478. else {
  90479. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90480. }
  90481. }
  90482. }
  90483. }
  90484. }
  90485. };
  90486. /**
  90487. * Enables rotation on the specified axis and disables rotation on the others
  90488. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90489. */
  90490. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90491. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90492. if (i < 4) {
  90493. m.setEnabled(axis.indexOf("x") != -1);
  90494. }
  90495. else if (i < 8) {
  90496. m.setEnabled(axis.indexOf("y") != -1);
  90497. }
  90498. else {
  90499. m.setEnabled(axis.indexOf("z") != -1);
  90500. }
  90501. });
  90502. };
  90503. /**
  90504. * Disposes of the gizmo
  90505. */
  90506. BoundingBoxGizmo.prototype.dispose = function () {
  90507. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90508. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90509. this._lineBoundingBox.dispose();
  90510. this._rotateSpheresParent.dispose();
  90511. this._scaleBoxesParent.dispose();
  90512. _super.prototype.dispose.call(this);
  90513. };
  90514. /**
  90515. * 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)
  90516. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  90517. * @returns the bounding box mesh with the passed in mesh as a child
  90518. */
  90519. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  90520. var makeNotPickable = function (root) {
  90521. root.isPickable = false;
  90522. root.getChildMeshes().forEach(function (c) {
  90523. makeNotPickable(c);
  90524. });
  90525. };
  90526. makeNotPickable(mesh);
  90527. // Reset position to get boudning box from origin with no rotation
  90528. if (!mesh.rotationQuaternion) {
  90529. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  90530. }
  90531. var oldPos = mesh.position.clone();
  90532. var oldRot = mesh.rotationQuaternion.clone();
  90533. mesh.rotationQuaternion.set(0, 0, 0, 1);
  90534. mesh.position.set(0, 0, 0);
  90535. // Update bounding dimensions/positions
  90536. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  90537. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  90538. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  90539. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90540. // Restore original positions
  90541. mesh.addChild(box);
  90542. mesh.rotationQuaternion.copyFrom(oldRot);
  90543. mesh.position.copyFrom(oldPos);
  90544. // Reverse parenting
  90545. mesh.removeChild(box);
  90546. box.addChild(mesh);
  90547. box.visibility = 0;
  90548. return box;
  90549. };
  90550. return BoundingBoxGizmo;
  90551. }(BABYLON.Gizmo));
  90552. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90553. })(BABYLON || (BABYLON = {}));
  90554. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90555. var BABYLON;
  90556. (function (BABYLON) {
  90557. /**
  90558. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90559. */
  90560. var GizmoManager = /** @class */ (function () {
  90561. /**
  90562. * Instatiates a gizmo manager
  90563. * @param scene the scene to overlay the gizmos on top of
  90564. */
  90565. function GizmoManager(scene) {
  90566. var _this = this;
  90567. this.scene = scene;
  90568. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  90569. this._pointerObserver = null;
  90570. this._attachedMesh = null;
  90571. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  90572. this._boundingBoxUtilLayer = null;
  90573. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  90574. /**
  90575. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  90576. */
  90577. this.attachableMeshes = null;
  90578. /**
  90579. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  90580. */
  90581. this.usePointerToAttachGizmos = true;
  90582. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  90583. // Instatiate/dispose gizmos based on pointer actions
  90584. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90585. if (!_this.usePointerToAttachGizmos) {
  90586. return;
  90587. }
  90588. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90589. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90590. var node = pointerInfo.pickInfo.pickedMesh;
  90591. if (_this.attachableMeshes == null) {
  90592. // Attach to the most parent node
  90593. while (node && node.parent != null) {
  90594. node = node.parent;
  90595. }
  90596. }
  90597. else {
  90598. // Attach to the parent node that is an attachableMesh
  90599. var found = false;
  90600. _this.attachableMeshes.forEach(function (mesh) {
  90601. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  90602. node = mesh;
  90603. found = true;
  90604. }
  90605. });
  90606. if (!found) {
  90607. node = null;
  90608. }
  90609. }
  90610. if (node instanceof BABYLON.AbstractMesh) {
  90611. _this.attachToMesh(node);
  90612. }
  90613. }
  90614. else {
  90615. _this.attachToMesh(null);
  90616. }
  90617. }
  90618. });
  90619. }
  90620. /**
  90621. * Attaches a set of gizmos to the specified mesh
  90622. * @param mesh The mesh the gizmo's should be attached to
  90623. */
  90624. GizmoManager.prototype.attachToMesh = function (mesh) {
  90625. if (this._attachedMesh) {
  90626. this._attachedMesh.removeBehavior(this._dragBehavior);
  90627. }
  90628. this._attachedMesh = mesh;
  90629. for (var key in this.gizmos) {
  90630. var gizmo = (this.gizmos[key]);
  90631. if (gizmo && this._gizmosEnabled[key]) {
  90632. gizmo.attachedMesh = mesh;
  90633. }
  90634. }
  90635. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  90636. this._attachedMesh.addBehavior(this._dragBehavior);
  90637. }
  90638. };
  90639. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  90640. get: function () {
  90641. return this._gizmosEnabled.positionGizmo;
  90642. },
  90643. /**
  90644. * If the position gizmo is enabled
  90645. */
  90646. set: function (value) {
  90647. if (value) {
  90648. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  90649. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90650. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  90651. }
  90652. else if (this.gizmos.positionGizmo) {
  90653. this.gizmos.positionGizmo.attachedMesh = null;
  90654. }
  90655. this._gizmosEnabled.positionGizmo = value;
  90656. },
  90657. enumerable: true,
  90658. configurable: true
  90659. });
  90660. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  90661. get: function () {
  90662. return this._gizmosEnabled.rotationGizmo;
  90663. },
  90664. /**
  90665. * If the rotation gizmo is enabled
  90666. */
  90667. set: function (value) {
  90668. if (value) {
  90669. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  90670. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90671. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  90672. }
  90673. else if (this.gizmos.rotationGizmo) {
  90674. this.gizmos.rotationGizmo.attachedMesh = null;
  90675. }
  90676. this._gizmosEnabled.rotationGizmo = value;
  90677. },
  90678. enumerable: true,
  90679. configurable: true
  90680. });
  90681. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  90682. get: function () {
  90683. return this._gizmosEnabled.scaleGizmo;
  90684. },
  90685. /**
  90686. * If the scale gizmo is enabled
  90687. */
  90688. set: function (value) {
  90689. if (value) {
  90690. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  90691. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  90692. }
  90693. else if (this.gizmos.scaleGizmo) {
  90694. this.gizmos.scaleGizmo.attachedMesh = null;
  90695. }
  90696. this._gizmosEnabled.scaleGizmo = value;
  90697. },
  90698. enumerable: true,
  90699. configurable: true
  90700. });
  90701. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  90702. get: function () {
  90703. return this._gizmosEnabled.boundingBoxGizmo;
  90704. },
  90705. /**
  90706. * If the boundingBox gizmo is enabled
  90707. */
  90708. set: function (value) {
  90709. if (value) {
  90710. if (!this._boundingBoxUtilLayer) {
  90711. this._boundingBoxUtilLayer = new BABYLON.UtilityLayerRenderer(this.scene);
  90712. this._boundingBoxUtilLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90713. }
  90714. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._boundingBoxUtilLayer);
  90715. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  90716. if (this._attachedMesh) {
  90717. this._attachedMesh.removeBehavior(this._dragBehavior);
  90718. this._attachedMesh.addBehavior(this._dragBehavior);
  90719. }
  90720. }
  90721. else if (this.gizmos.boundingBoxGizmo) {
  90722. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  90723. }
  90724. this._gizmosEnabled.boundingBoxGizmo = value;
  90725. },
  90726. enumerable: true,
  90727. configurable: true
  90728. });
  90729. /**
  90730. * Disposes of the gizmo manager
  90731. */
  90732. GizmoManager.prototype.dispose = function () {
  90733. this.scene.onPointerObservable.remove(this._pointerObserver);
  90734. for (var key in this.gizmos) {
  90735. var gizmo = (this.gizmos[key]);
  90736. if (gizmo) {
  90737. gizmo.dispose();
  90738. }
  90739. }
  90740. this._gizmoLayer.dispose();
  90741. };
  90742. return GizmoManager;
  90743. }());
  90744. BABYLON.GizmoManager = GizmoManager;
  90745. })(BABYLON || (BABYLON = {}));
  90746. //# sourceMappingURL=babylon.gizmoManager.js.map
  90747. var BABYLON;
  90748. (function (BABYLON) {
  90749. /**
  90750. * Defines a target to use with MorphTargetManager
  90751. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90752. */
  90753. var MorphTarget = /** @class */ (function () {
  90754. /**
  90755. * Creates a new MorphTarget
  90756. * @param name defines the name of the target
  90757. * @param influence defines the influence to use
  90758. */
  90759. function MorphTarget(
  90760. /** defines the name of the target */
  90761. name, influence, scene) {
  90762. if (influence === void 0) { influence = 0; }
  90763. if (scene === void 0) { scene = null; }
  90764. this.name = name;
  90765. /**
  90766. * Gets or sets the list of animations
  90767. */
  90768. this.animations = new Array();
  90769. this._positions = null;
  90770. this._normals = null;
  90771. this._tangents = null;
  90772. /**
  90773. * Observable raised when the influence changes
  90774. */
  90775. this.onInfluenceChanged = new BABYLON.Observable();
  90776. this._animationPropertiesOverride = null;
  90777. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90778. this.influence = influence;
  90779. }
  90780. Object.defineProperty(MorphTarget.prototype, "influence", {
  90781. /**
  90782. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90783. */
  90784. get: function () {
  90785. return this._influence;
  90786. },
  90787. set: function (influence) {
  90788. if (this._influence === influence) {
  90789. return;
  90790. }
  90791. var previous = this._influence;
  90792. this._influence = influence;
  90793. if (this.onInfluenceChanged.hasObservers) {
  90794. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90795. }
  90796. },
  90797. enumerable: true,
  90798. configurable: true
  90799. });
  90800. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90801. /**
  90802. * Gets or sets the animation properties override
  90803. */
  90804. get: function () {
  90805. if (!this._animationPropertiesOverride && this._scene) {
  90806. return this._scene.animationPropertiesOverride;
  90807. }
  90808. return this._animationPropertiesOverride;
  90809. },
  90810. set: function (value) {
  90811. this._animationPropertiesOverride = value;
  90812. },
  90813. enumerable: true,
  90814. configurable: true
  90815. });
  90816. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90817. /**
  90818. * Gets a boolean defining if the target contains position data
  90819. */
  90820. get: function () {
  90821. return !!this._positions;
  90822. },
  90823. enumerable: true,
  90824. configurable: true
  90825. });
  90826. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90827. /**
  90828. * Gets a boolean defining if the target contains normal data
  90829. */
  90830. get: function () {
  90831. return !!this._normals;
  90832. },
  90833. enumerable: true,
  90834. configurable: true
  90835. });
  90836. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90837. /**
  90838. * Gets a boolean defining if the target contains tangent data
  90839. */
  90840. get: function () {
  90841. return !!this._tangents;
  90842. },
  90843. enumerable: true,
  90844. configurable: true
  90845. });
  90846. /**
  90847. * Affects position data to this target
  90848. * @param data defines the position data to use
  90849. */
  90850. MorphTarget.prototype.setPositions = function (data) {
  90851. this._positions = data;
  90852. };
  90853. /**
  90854. * Gets the position data stored in this target
  90855. * @returns a FloatArray containing the position data (or null if not present)
  90856. */
  90857. MorphTarget.prototype.getPositions = function () {
  90858. return this._positions;
  90859. };
  90860. /**
  90861. * Affects normal data to this target
  90862. * @param data defines the normal data to use
  90863. */
  90864. MorphTarget.prototype.setNormals = function (data) {
  90865. this._normals = data;
  90866. };
  90867. /**
  90868. * Gets the normal data stored in this target
  90869. * @returns a FloatArray containing the normal data (or null if not present)
  90870. */
  90871. MorphTarget.prototype.getNormals = function () {
  90872. return this._normals;
  90873. };
  90874. /**
  90875. * Affects tangent data to this target
  90876. * @param data defines the tangent data to use
  90877. */
  90878. MorphTarget.prototype.setTangents = function (data) {
  90879. this._tangents = data;
  90880. };
  90881. /**
  90882. * Gets the tangent data stored in this target
  90883. * @returns a FloatArray containing the tangent data (or null if not present)
  90884. */
  90885. MorphTarget.prototype.getTangents = function () {
  90886. return this._tangents;
  90887. };
  90888. /**
  90889. * Serializes the current target into a Serialization object
  90890. * @returns the serialized object
  90891. */
  90892. MorphTarget.prototype.serialize = function () {
  90893. var serializationObject = {};
  90894. serializationObject.name = this.name;
  90895. serializationObject.influence = this.influence;
  90896. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90897. if (this.hasNormals) {
  90898. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90899. }
  90900. if (this.hasTangents) {
  90901. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90902. }
  90903. // Animations
  90904. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90905. return serializationObject;
  90906. };
  90907. // Statics
  90908. /**
  90909. * Creates a new target from serialized data
  90910. * @param serializationObject defines the serialized data to use
  90911. * @returns a new MorphTarget
  90912. */
  90913. MorphTarget.Parse = function (serializationObject) {
  90914. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90915. result.setPositions(serializationObject.positions);
  90916. if (serializationObject.normals) {
  90917. result.setNormals(serializationObject.normals);
  90918. }
  90919. if (serializationObject.tangents) {
  90920. result.setTangents(serializationObject.tangents);
  90921. }
  90922. // Animations
  90923. if (serializationObject.animations) {
  90924. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90925. var parsedAnimation = serializationObject.animations[animationIndex];
  90926. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90927. }
  90928. }
  90929. return result;
  90930. };
  90931. /**
  90932. * Creates a MorphTarget from mesh data
  90933. * @param mesh defines the source mesh
  90934. * @param name defines the name to use for the new target
  90935. * @param influence defines the influence to attach to the target
  90936. * @returns a new MorphTarget
  90937. */
  90938. MorphTarget.FromMesh = function (mesh, name, influence) {
  90939. if (!name) {
  90940. name = mesh.name;
  90941. }
  90942. var result = new MorphTarget(name, influence, mesh.getScene());
  90943. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90944. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90945. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90946. }
  90947. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90948. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90949. }
  90950. return result;
  90951. };
  90952. return MorphTarget;
  90953. }());
  90954. BABYLON.MorphTarget = MorphTarget;
  90955. })(BABYLON || (BABYLON = {}));
  90956. //# sourceMappingURL=babylon.morphTarget.js.map
  90957. var BABYLON;
  90958. (function (BABYLON) {
  90959. /**
  90960. * This class is used to deform meshes using morphing between different targets
  90961. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90962. */
  90963. var MorphTargetManager = /** @class */ (function () {
  90964. /**
  90965. * Creates a new MorphTargetManager
  90966. * @param scene defines the current scene
  90967. */
  90968. function MorphTargetManager(scene) {
  90969. if (scene === void 0) { scene = null; }
  90970. this._targets = new Array();
  90971. this._targetObservable = new Array();
  90972. this._activeTargets = new BABYLON.SmartArray(16);
  90973. this._supportsNormals = false;
  90974. this._supportsTangents = false;
  90975. this._vertexCount = 0;
  90976. this._uniqueId = 0;
  90977. this._tempInfluences = new Array();
  90978. if (!scene) {
  90979. scene = BABYLON.Engine.LastCreatedScene;
  90980. }
  90981. this._scene = scene;
  90982. if (this._scene) {
  90983. this._scene.morphTargetManagers.push(this);
  90984. this._uniqueId = this._scene.getUniqueId();
  90985. }
  90986. }
  90987. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90988. /**
  90989. * Gets the unique ID of this manager
  90990. */
  90991. get: function () {
  90992. return this._uniqueId;
  90993. },
  90994. enumerable: true,
  90995. configurable: true
  90996. });
  90997. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90998. /**
  90999. * Gets the number of vertices handled by this manager
  91000. */
  91001. get: function () {
  91002. return this._vertexCount;
  91003. },
  91004. enumerable: true,
  91005. configurable: true
  91006. });
  91007. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  91008. /**
  91009. * Gets a boolean indicating if this manager supports morphing of normals
  91010. */
  91011. get: function () {
  91012. return this._supportsNormals;
  91013. },
  91014. enumerable: true,
  91015. configurable: true
  91016. });
  91017. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  91018. /**
  91019. * Gets a boolean indicating if this manager supports morphing of tangents
  91020. */
  91021. get: function () {
  91022. return this._supportsTangents;
  91023. },
  91024. enumerable: true,
  91025. configurable: true
  91026. });
  91027. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  91028. /**
  91029. * Gets the number of targets stored in this manager
  91030. */
  91031. get: function () {
  91032. return this._targets.length;
  91033. },
  91034. enumerable: true,
  91035. configurable: true
  91036. });
  91037. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  91038. /**
  91039. * Gets the number of influencers (ie. the number of targets with influences > 0)
  91040. */
  91041. get: function () {
  91042. return this._activeTargets.length;
  91043. },
  91044. enumerable: true,
  91045. configurable: true
  91046. });
  91047. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  91048. /**
  91049. * Gets the list of influences (one per target)
  91050. */
  91051. get: function () {
  91052. return this._influences;
  91053. },
  91054. enumerable: true,
  91055. configurable: true
  91056. });
  91057. /**
  91058. * Gets the active target at specified index. An active target is a target with an influence > 0
  91059. * @param index defines the index to check
  91060. * @returns the requested target
  91061. */
  91062. MorphTargetManager.prototype.getActiveTarget = function (index) {
  91063. return this._activeTargets.data[index];
  91064. };
  91065. /**
  91066. * Gets the target at specified index
  91067. * @param index defines the index to check
  91068. * @returns the requested target
  91069. */
  91070. MorphTargetManager.prototype.getTarget = function (index) {
  91071. return this._targets[index];
  91072. };
  91073. /**
  91074. * Add a new target to this manager
  91075. * @param target defines the target to add
  91076. */
  91077. MorphTargetManager.prototype.addTarget = function (target) {
  91078. var _this = this;
  91079. this._targets.push(target);
  91080. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  91081. _this._syncActiveTargets(needUpdate);
  91082. }));
  91083. this._syncActiveTargets(true);
  91084. };
  91085. /**
  91086. * Removes a target from the manager
  91087. * @param target defines the target to remove
  91088. */
  91089. MorphTargetManager.prototype.removeTarget = function (target) {
  91090. var index = this._targets.indexOf(target);
  91091. if (index >= 0) {
  91092. this._targets.splice(index, 1);
  91093. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  91094. this._syncActiveTargets(true);
  91095. }
  91096. };
  91097. /**
  91098. * Serializes the current manager into a Serialization object
  91099. * @returns the serialized object
  91100. */
  91101. MorphTargetManager.prototype.serialize = function () {
  91102. var serializationObject = {};
  91103. serializationObject.id = this.uniqueId;
  91104. serializationObject.targets = [];
  91105. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91106. var target = _a[_i];
  91107. serializationObject.targets.push(target.serialize());
  91108. }
  91109. return serializationObject;
  91110. };
  91111. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  91112. var influenceCount = 0;
  91113. this._activeTargets.reset();
  91114. this._supportsNormals = true;
  91115. this._supportsTangents = true;
  91116. this._vertexCount = 0;
  91117. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91118. var target = _a[_i];
  91119. this._activeTargets.push(target);
  91120. this._tempInfluences[influenceCount++] = target.influence;
  91121. var positions = target.getPositions();
  91122. if (positions) {
  91123. this._supportsNormals = this._supportsNormals && target.hasNormals;
  91124. this._supportsTangents = this._supportsTangents && target.hasTangents;
  91125. var vertexCount = positions.length / 3;
  91126. if (this._vertexCount === 0) {
  91127. this._vertexCount = vertexCount;
  91128. }
  91129. else if (this._vertexCount !== vertexCount) {
  91130. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  91131. return;
  91132. }
  91133. }
  91134. }
  91135. if (!this._influences || this._influences.length !== influenceCount) {
  91136. this._influences = new Float32Array(influenceCount);
  91137. }
  91138. for (var index = 0; index < influenceCount; index++) {
  91139. this._influences[index] = this._tempInfluences[index];
  91140. }
  91141. if (needUpdate) {
  91142. this.synchronize();
  91143. }
  91144. };
  91145. /**
  91146. * Syncrhonize the targets with all the meshes using this morph target manager
  91147. */
  91148. MorphTargetManager.prototype.synchronize = function () {
  91149. if (!this._scene) {
  91150. return;
  91151. }
  91152. // Flag meshes as dirty to resync with the active targets
  91153. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  91154. var mesh = _a[_i];
  91155. if (mesh.morphTargetManager === this) {
  91156. mesh._syncGeometryWithMorphTargetManager();
  91157. }
  91158. }
  91159. };
  91160. // Statics
  91161. /**
  91162. * Creates a new MorphTargetManager from serialized data
  91163. * @param serializationObject defines the serialized data
  91164. * @param scene defines the hosting scene
  91165. * @returns the new MorphTargetManager
  91166. */
  91167. MorphTargetManager.Parse = function (serializationObject, scene) {
  91168. var result = new MorphTargetManager(scene);
  91169. result._uniqueId = serializationObject.id;
  91170. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91171. var targetData = _a[_i];
  91172. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91173. }
  91174. return result;
  91175. };
  91176. return MorphTargetManager;
  91177. }());
  91178. BABYLON.MorphTargetManager = MorphTargetManager;
  91179. })(BABYLON || (BABYLON = {}));
  91180. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91181. var BABYLON;
  91182. (function (BABYLON) {
  91183. var Octree = /** @class */ (function () {
  91184. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91185. if (maxDepth === void 0) { maxDepth = 2; }
  91186. this.maxDepth = maxDepth;
  91187. this.dynamicContent = new Array();
  91188. this._maxBlockCapacity = maxBlockCapacity || 64;
  91189. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91190. this._creationFunc = creationFunc;
  91191. }
  91192. // Methods
  91193. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91194. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91195. };
  91196. Octree.prototype.addMesh = function (entry) {
  91197. for (var index = 0; index < this.blocks.length; index++) {
  91198. var block = this.blocks[index];
  91199. block.addEntry(entry);
  91200. }
  91201. };
  91202. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91203. this._selectionContent.reset();
  91204. for (var index = 0; index < this.blocks.length; index++) {
  91205. var block = this.blocks[index];
  91206. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91207. }
  91208. if (allowDuplicate) {
  91209. this._selectionContent.concat(this.dynamicContent);
  91210. }
  91211. else {
  91212. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91213. }
  91214. return this._selectionContent;
  91215. };
  91216. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91217. this._selectionContent.reset();
  91218. for (var index = 0; index < this.blocks.length; index++) {
  91219. var block = this.blocks[index];
  91220. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91221. }
  91222. if (allowDuplicate) {
  91223. this._selectionContent.concat(this.dynamicContent);
  91224. }
  91225. else {
  91226. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91227. }
  91228. return this._selectionContent;
  91229. };
  91230. Octree.prototype.intersectsRay = function (ray) {
  91231. this._selectionContent.reset();
  91232. for (var index = 0; index < this.blocks.length; index++) {
  91233. var block = this.blocks[index];
  91234. block.intersectsRay(ray, this._selectionContent);
  91235. }
  91236. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91237. return this._selectionContent;
  91238. };
  91239. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91240. target.blocks = new Array();
  91241. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91242. // Segmenting space
  91243. for (var x = 0; x < 2; x++) {
  91244. for (var y = 0; y < 2; y++) {
  91245. for (var z = 0; z < 2; z++) {
  91246. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91247. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91248. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91249. block.addEntries(entries);
  91250. target.blocks.push(block);
  91251. }
  91252. }
  91253. }
  91254. };
  91255. Octree.CreationFuncForMeshes = function (entry, block) {
  91256. var boundingInfo = entry.getBoundingInfo();
  91257. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91258. block.entries.push(entry);
  91259. }
  91260. };
  91261. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91262. var boundingInfo = entry.getBoundingInfo();
  91263. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91264. block.entries.push(entry);
  91265. }
  91266. };
  91267. return Octree;
  91268. }());
  91269. BABYLON.Octree = Octree;
  91270. })(BABYLON || (BABYLON = {}));
  91271. //# sourceMappingURL=babylon.octree.js.map
  91272. var BABYLON;
  91273. (function (BABYLON) {
  91274. var OctreeBlock = /** @class */ (function () {
  91275. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91276. this.entries = new Array();
  91277. this._boundingVectors = new Array();
  91278. this._capacity = capacity;
  91279. this._depth = depth;
  91280. this._maxDepth = maxDepth;
  91281. this._creationFunc = creationFunc;
  91282. this._minPoint = minPoint;
  91283. this._maxPoint = maxPoint;
  91284. this._boundingVectors.push(minPoint.clone());
  91285. this._boundingVectors.push(maxPoint.clone());
  91286. this._boundingVectors.push(minPoint.clone());
  91287. this._boundingVectors[2].x = maxPoint.x;
  91288. this._boundingVectors.push(minPoint.clone());
  91289. this._boundingVectors[3].y = maxPoint.y;
  91290. this._boundingVectors.push(minPoint.clone());
  91291. this._boundingVectors[4].z = maxPoint.z;
  91292. this._boundingVectors.push(maxPoint.clone());
  91293. this._boundingVectors[5].z = minPoint.z;
  91294. this._boundingVectors.push(maxPoint.clone());
  91295. this._boundingVectors[6].x = minPoint.x;
  91296. this._boundingVectors.push(maxPoint.clone());
  91297. this._boundingVectors[7].y = minPoint.y;
  91298. }
  91299. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91300. // Property
  91301. get: function () {
  91302. return this._capacity;
  91303. },
  91304. enumerable: true,
  91305. configurable: true
  91306. });
  91307. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91308. get: function () {
  91309. return this._minPoint;
  91310. },
  91311. enumerable: true,
  91312. configurable: true
  91313. });
  91314. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91315. get: function () {
  91316. return this._maxPoint;
  91317. },
  91318. enumerable: true,
  91319. configurable: true
  91320. });
  91321. // Methods
  91322. OctreeBlock.prototype.addEntry = function (entry) {
  91323. if (this.blocks) {
  91324. for (var index = 0; index < this.blocks.length; index++) {
  91325. var block = this.blocks[index];
  91326. block.addEntry(entry);
  91327. }
  91328. return;
  91329. }
  91330. this._creationFunc(entry, this);
  91331. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91332. this.createInnerBlocks();
  91333. }
  91334. };
  91335. OctreeBlock.prototype.addEntries = function (entries) {
  91336. for (var index = 0; index < entries.length; index++) {
  91337. var mesh = entries[index];
  91338. this.addEntry(mesh);
  91339. }
  91340. };
  91341. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91342. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91343. if (this.blocks) {
  91344. for (var index = 0; index < this.blocks.length; index++) {
  91345. var block = this.blocks[index];
  91346. block.select(frustumPlanes, selection, allowDuplicate);
  91347. }
  91348. return;
  91349. }
  91350. if (allowDuplicate) {
  91351. selection.concat(this.entries);
  91352. }
  91353. else {
  91354. selection.concatWithNoDuplicate(this.entries);
  91355. }
  91356. }
  91357. };
  91358. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91359. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91360. if (this.blocks) {
  91361. for (var index = 0; index < this.blocks.length; index++) {
  91362. var block = this.blocks[index];
  91363. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91364. }
  91365. return;
  91366. }
  91367. if (allowDuplicate) {
  91368. selection.concat(this.entries);
  91369. }
  91370. else {
  91371. selection.concatWithNoDuplicate(this.entries);
  91372. }
  91373. }
  91374. };
  91375. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91376. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91377. if (this.blocks) {
  91378. for (var index = 0; index < this.blocks.length; index++) {
  91379. var block = this.blocks[index];
  91380. block.intersectsRay(ray, selection);
  91381. }
  91382. return;
  91383. }
  91384. selection.concatWithNoDuplicate(this.entries);
  91385. }
  91386. };
  91387. OctreeBlock.prototype.createInnerBlocks = function () {
  91388. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91389. };
  91390. return OctreeBlock;
  91391. }());
  91392. BABYLON.OctreeBlock = OctreeBlock;
  91393. })(BABYLON || (BABYLON = {}));
  91394. //# sourceMappingURL=babylon.octreeBlock.js.map
  91395. var BABYLON;
  91396. (function (BABYLON) {
  91397. /**
  91398. * Postprocess used to generate anaglyphic rendering
  91399. */
  91400. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91401. __extends(AnaglyphPostProcess, _super);
  91402. /**
  91403. * Creates a new AnaglyphPostProcess
  91404. * @param name defines postprocess name
  91405. * @param options defines creation options or target ratio scale
  91406. * @param rigCameras defines cameras using this postprocess
  91407. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91408. * @param engine defines hosting engine
  91409. * @param reusable defines if the postprocess will be reused multiple times per frame
  91410. */
  91411. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91412. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91413. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91414. _this.onApplyObservable.add(function (effect) {
  91415. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91416. });
  91417. return _this;
  91418. }
  91419. return AnaglyphPostProcess;
  91420. }(BABYLON.PostProcess));
  91421. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91422. })(BABYLON || (BABYLON = {}));
  91423. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91424. var BABYLON;
  91425. (function (BABYLON) {
  91426. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91427. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91428. });
  91429. /**
  91430. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91431. */
  91432. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91433. __extends(AnaglyphArcRotateCamera, _super);
  91434. /**
  91435. * Creates a new AnaglyphArcRotateCamera
  91436. * @param name defines camera name
  91437. * @param alpha defines alpha angle (in radians)
  91438. * @param beta defines beta angle (in radians)
  91439. * @param radius defines radius
  91440. * @param target defines camera target
  91441. * @param interaxialDistance defines distance between each color axis
  91442. * @param scene defines the hosting scene
  91443. */
  91444. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91445. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91446. _this.interaxialDistance = interaxialDistance;
  91447. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91448. return _this;
  91449. }
  91450. /**
  91451. * Gets camera class name
  91452. * @returns AnaglyphArcRotateCamera
  91453. */
  91454. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91455. return "AnaglyphArcRotateCamera";
  91456. };
  91457. return AnaglyphArcRotateCamera;
  91458. }(BABYLON.ArcRotateCamera));
  91459. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91460. })(BABYLON || (BABYLON = {}));
  91461. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91462. var BABYLON;
  91463. (function (BABYLON) {
  91464. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91465. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91466. });
  91467. /**
  91468. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91469. */
  91470. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91471. __extends(AnaglyphFreeCamera, _super);
  91472. /**
  91473. * Creates a new AnaglyphFreeCamera
  91474. * @param name defines camera name
  91475. * @param position defines initial position
  91476. * @param interaxialDistance defines distance between each color axis
  91477. * @param scene defines the hosting scene
  91478. */
  91479. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91480. var _this = _super.call(this, name, position, scene) || this;
  91481. _this.interaxialDistance = interaxialDistance;
  91482. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91483. return _this;
  91484. }
  91485. /**
  91486. * Gets camera class name
  91487. * @returns AnaglyphFreeCamera
  91488. */
  91489. AnaglyphFreeCamera.prototype.getClassName = function () {
  91490. return "AnaglyphFreeCamera";
  91491. };
  91492. return AnaglyphFreeCamera;
  91493. }(BABYLON.FreeCamera));
  91494. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91495. })(BABYLON || (BABYLON = {}));
  91496. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91497. var BABYLON;
  91498. (function (BABYLON) {
  91499. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91500. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91501. });
  91502. /**
  91503. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91504. */
  91505. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91506. __extends(AnaglyphGamepadCamera, _super);
  91507. /**
  91508. * Creates a new AnaglyphGamepadCamera
  91509. * @param name defines camera name
  91510. * @param position defines initial position
  91511. * @param interaxialDistance defines distance between each color axis
  91512. * @param scene defines the hosting scene
  91513. */
  91514. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91515. var _this = _super.call(this, name, position, scene) || this;
  91516. _this.interaxialDistance = interaxialDistance;
  91517. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91518. return _this;
  91519. }
  91520. /**
  91521. * Gets camera class name
  91522. * @returns AnaglyphGamepadCamera
  91523. */
  91524. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91525. return "AnaglyphGamepadCamera";
  91526. };
  91527. return AnaglyphGamepadCamera;
  91528. }(BABYLON.GamepadCamera));
  91529. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91530. })(BABYLON || (BABYLON = {}));
  91531. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  91532. var BABYLON;
  91533. (function (BABYLON) {
  91534. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  91535. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91536. });
  91537. /**
  91538. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91539. */
  91540. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91541. __extends(AnaglyphUniversalCamera, _super);
  91542. /**
  91543. * Creates a new AnaglyphUniversalCamera
  91544. * @param name defines camera name
  91545. * @param position defines initial position
  91546. * @param interaxialDistance defines distance between each color axis
  91547. * @param scene defines the hosting scene
  91548. */
  91549. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91550. var _this = _super.call(this, name, position, scene) || this;
  91551. _this.interaxialDistance = interaxialDistance;
  91552. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91553. return _this;
  91554. }
  91555. /**
  91556. * Gets camera class name
  91557. * @returns AnaglyphUniversalCamera
  91558. */
  91559. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91560. return "AnaglyphUniversalCamera";
  91561. };
  91562. return AnaglyphUniversalCamera;
  91563. }(BABYLON.UniversalCamera));
  91564. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91565. })(BABYLON || (BABYLON = {}));
  91566. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  91567. var BABYLON;
  91568. (function (BABYLON) {
  91569. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  91570. __extends(StereoscopicInterlacePostProcess, _super);
  91571. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  91572. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  91573. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91574. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91575. _this.onSizeChangedObservable.add(function () {
  91576. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91577. });
  91578. _this.onApplyObservable.add(function (effect) {
  91579. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  91580. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  91581. });
  91582. return _this;
  91583. }
  91584. return StereoscopicInterlacePostProcess;
  91585. }(BABYLON.PostProcess));
  91586. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  91587. })(BABYLON || (BABYLON = {}));
  91588. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  91589. var BABYLON;
  91590. (function (BABYLON) {
  91591. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  91592. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91593. });
  91594. /**
  91595. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91596. */
  91597. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91598. __extends(StereoscopicArcRotateCamera, _super);
  91599. /**
  91600. * Creates a new StereoscopicArcRotateCamera
  91601. * @param name defines camera name
  91602. * @param alpha defines alpha angle (in radians)
  91603. * @param beta defines beta angle (in radians)
  91604. * @param radius defines radius
  91605. * @param target defines camera target
  91606. * @param interaxialDistance defines distance between each color axis
  91607. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91608. * @param scene defines the hosting scene
  91609. */
  91610. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91611. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91612. _this.interaxialDistance = interaxialDistance;
  91613. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91614. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91615. return _this;
  91616. }
  91617. /**
  91618. * Gets camera class name
  91619. * @returns StereoscopicArcRotateCamera
  91620. */
  91621. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91622. return "StereoscopicArcRotateCamera";
  91623. };
  91624. return StereoscopicArcRotateCamera;
  91625. }(BABYLON.ArcRotateCamera));
  91626. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91627. })(BABYLON || (BABYLON = {}));
  91628. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  91629. var BABYLON;
  91630. (function (BABYLON) {
  91631. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91632. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91633. });
  91634. /**
  91635. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91636. */
  91637. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91638. __extends(StereoscopicFreeCamera, _super);
  91639. /**
  91640. * Creates a new StereoscopicFreeCamera
  91641. * @param name defines camera name
  91642. * @param position defines initial position
  91643. * @param interaxialDistance defines distance between each color axis
  91644. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91645. * @param scene defines the hosting scene
  91646. */
  91647. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91648. var _this = _super.call(this, name, position, scene) || this;
  91649. _this.interaxialDistance = interaxialDistance;
  91650. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91651. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91652. return _this;
  91653. }
  91654. /**
  91655. * Gets camera class name
  91656. * @returns StereoscopicFreeCamera
  91657. */
  91658. StereoscopicFreeCamera.prototype.getClassName = function () {
  91659. return "StereoscopicFreeCamera";
  91660. };
  91661. return StereoscopicFreeCamera;
  91662. }(BABYLON.FreeCamera));
  91663. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91664. })(BABYLON || (BABYLON = {}));
  91665. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  91666. var BABYLON;
  91667. (function (BABYLON) {
  91668. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  91669. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91670. });
  91671. /**
  91672. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91673. */
  91674. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91675. __extends(StereoscopicGamepadCamera, _super);
  91676. /**
  91677. * Creates a new StereoscopicGamepadCamera
  91678. * @param name defines camera name
  91679. * @param position defines initial position
  91680. * @param interaxialDistance defines distance between each color axis
  91681. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91682. * @param scene defines the hosting scene
  91683. */
  91684. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91685. var _this = _super.call(this, name, position, scene) || this;
  91686. _this.interaxialDistance = interaxialDistance;
  91687. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91688. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91689. return _this;
  91690. }
  91691. /**
  91692. * Gets camera class name
  91693. * @returns StereoscopicGamepadCamera
  91694. */
  91695. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91696. return "StereoscopicGamepadCamera";
  91697. };
  91698. return StereoscopicGamepadCamera;
  91699. }(BABYLON.GamepadCamera));
  91700. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91701. })(BABYLON || (BABYLON = {}));
  91702. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  91703. var BABYLON;
  91704. (function (BABYLON) {
  91705. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91706. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91707. });
  91708. /**
  91709. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91710. */
  91711. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91712. __extends(StereoscopicUniversalCamera, _super);
  91713. /**
  91714. * Creates a new StereoscopicUniversalCamera
  91715. * @param name defines camera name
  91716. * @param position defines initial position
  91717. * @param interaxialDistance defines distance between each color axis
  91718. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91719. * @param scene defines the hosting scene
  91720. */
  91721. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91722. var _this = _super.call(this, name, position, scene) || this;
  91723. _this.interaxialDistance = interaxialDistance;
  91724. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91725. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91726. return _this;
  91727. }
  91728. /**
  91729. * Gets camera class name
  91730. * @returns StereoscopicUniversalCamera
  91731. */
  91732. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91733. return "StereoscopicUniversalCamera";
  91734. };
  91735. return StereoscopicUniversalCamera;
  91736. }(BABYLON.UniversalCamera));
  91737. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91738. })(BABYLON || (BABYLON = {}));
  91739. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  91740. var BABYLON;
  91741. (function (BABYLON) {
  91742. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91743. __extends(VRDistortionCorrectionPostProcess, _super);
  91744. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91745. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91746. 'LensCenter',
  91747. 'Scale',
  91748. 'ScaleIn',
  91749. 'HmdWarpParam'
  91750. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91751. _this._isRightEye = isRightEye;
  91752. _this._distortionFactors = vrMetrics.distortionK;
  91753. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91754. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91755. _this.adaptScaleToCurrentViewport = true;
  91756. _this.onSizeChangedObservable.add(function () {
  91757. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91758. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91759. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91760. });
  91761. _this.onApplyObservable.add(function (effect) {
  91762. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91763. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91764. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91765. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91766. });
  91767. return _this;
  91768. }
  91769. return VRDistortionCorrectionPostProcess;
  91770. }(BABYLON.PostProcess));
  91771. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91772. })(BABYLON || (BABYLON = {}));
  91773. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91774. var BABYLON;
  91775. (function (BABYLON) {
  91776. /**
  91777. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91778. * Screen rotation is taken into account.
  91779. */
  91780. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91781. function FreeCameraDeviceOrientationInput() {
  91782. var _this = this;
  91783. this._screenOrientationAngle = 0;
  91784. this._screenQuaternion = new BABYLON.Quaternion();
  91785. this._alpha = 0;
  91786. this._beta = 0;
  91787. this._gamma = 0;
  91788. this._orientationChanged = function () {
  91789. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91790. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91791. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91792. };
  91793. this._deviceOrientation = function (evt) {
  91794. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91795. _this._beta = evt.beta !== null ? evt.beta : 0;
  91796. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91797. };
  91798. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91799. this._orientationChanged();
  91800. }
  91801. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91802. get: function () {
  91803. return this._camera;
  91804. },
  91805. set: function (camera) {
  91806. this._camera = camera;
  91807. if (this._camera != null && !this._camera.rotationQuaternion) {
  91808. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91809. }
  91810. },
  91811. enumerable: true,
  91812. configurable: true
  91813. });
  91814. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91815. window.addEventListener("orientationchange", this._orientationChanged);
  91816. window.addEventListener("deviceorientation", this._deviceOrientation);
  91817. //In certain cases, the attach control is called AFTER orientation was changed,
  91818. //So this is needed.
  91819. this._orientationChanged();
  91820. };
  91821. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91822. window.removeEventListener("orientationchange", this._orientationChanged);
  91823. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91824. };
  91825. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91826. //if no device orientation provided, don't update the rotation.
  91827. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91828. if (!this._alpha)
  91829. return;
  91830. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91831. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91832. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91833. //Mirror on XY Plane
  91834. this._camera.rotationQuaternion.z *= -1;
  91835. this._camera.rotationQuaternion.w *= -1;
  91836. };
  91837. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91838. return "FreeCameraDeviceOrientationInput";
  91839. };
  91840. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91841. return "deviceOrientation";
  91842. };
  91843. return FreeCameraDeviceOrientationInput;
  91844. }());
  91845. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91846. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91847. })(BABYLON || (BABYLON = {}));
  91848. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91849. var BABYLON;
  91850. (function (BABYLON) {
  91851. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91852. function ArcRotateCameraVRDeviceOrientationInput() {
  91853. this.alphaCorrection = 1;
  91854. this.betaCorrection = 1;
  91855. this.gammaCorrection = 1;
  91856. this._alpha = 0;
  91857. this._gamma = 0;
  91858. this._dirty = false;
  91859. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91860. }
  91861. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91862. this.camera.attachControl(element, noPreventDefault);
  91863. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91864. };
  91865. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91866. if (evt.alpha !== null) {
  91867. this._alpha = +evt.alpha | 0;
  91868. }
  91869. if (evt.gamma !== null) {
  91870. this._gamma = +evt.gamma | 0;
  91871. }
  91872. this._dirty = true;
  91873. };
  91874. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91875. if (this._dirty) {
  91876. this._dirty = false;
  91877. if (this._gamma < 0) {
  91878. this._gamma = 180 + this._gamma;
  91879. }
  91880. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91881. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91882. }
  91883. };
  91884. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91885. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91886. };
  91887. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91888. return "ArcRotateCameraVRDeviceOrientationInput";
  91889. };
  91890. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91891. return "VRDeviceOrientation";
  91892. };
  91893. return ArcRotateCameraVRDeviceOrientationInput;
  91894. }());
  91895. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91896. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91897. })(BABYLON || (BABYLON = {}));
  91898. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91899. var BABYLON;
  91900. (function (BABYLON) {
  91901. var VRCameraMetrics = /** @class */ (function () {
  91902. function VRCameraMetrics() {
  91903. this.compensateDistortion = true;
  91904. }
  91905. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91906. get: function () {
  91907. return this.hResolution / (2 * this.vResolution);
  91908. },
  91909. enumerable: true,
  91910. configurable: true
  91911. });
  91912. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91913. get: function () {
  91914. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91915. },
  91916. enumerable: true,
  91917. configurable: true
  91918. });
  91919. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91920. get: function () {
  91921. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91922. var h = (4 * meters) / this.hScreenSize;
  91923. return BABYLON.Matrix.Translation(h, 0, 0);
  91924. },
  91925. enumerable: true,
  91926. configurable: true
  91927. });
  91928. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91929. get: function () {
  91930. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91931. var h = (4 * meters) / this.hScreenSize;
  91932. return BABYLON.Matrix.Translation(-h, 0, 0);
  91933. },
  91934. enumerable: true,
  91935. configurable: true
  91936. });
  91937. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91938. get: function () {
  91939. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91940. },
  91941. enumerable: true,
  91942. configurable: true
  91943. });
  91944. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91945. get: function () {
  91946. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91947. },
  91948. enumerable: true,
  91949. configurable: true
  91950. });
  91951. VRCameraMetrics.GetDefault = function () {
  91952. var result = new VRCameraMetrics();
  91953. result.hResolution = 1280;
  91954. result.vResolution = 800;
  91955. result.hScreenSize = 0.149759993;
  91956. result.vScreenSize = 0.0935999975;
  91957. result.vScreenCenter = 0.0467999987;
  91958. result.eyeToScreenDistance = 0.0410000011;
  91959. result.lensSeparationDistance = 0.0635000020;
  91960. result.interpupillaryDistance = 0.0640000030;
  91961. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91962. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91963. result.postProcessScaleFactor = 1.714605507808412;
  91964. result.lensCenterOffset = 0.151976421;
  91965. return result;
  91966. };
  91967. return VRCameraMetrics;
  91968. }());
  91969. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91970. })(BABYLON || (BABYLON = {}));
  91971. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91972. var BABYLON;
  91973. (function (BABYLON) {
  91974. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  91975. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91976. });
  91977. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  91978. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91979. });
  91980. /**
  91981. * This represents a WebVR camera.
  91982. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91983. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91984. */
  91985. var WebVRFreeCamera = /** @class */ (function (_super) {
  91986. __extends(WebVRFreeCamera, _super);
  91987. /**
  91988. * Instantiates a WebVRFreeCamera.
  91989. * @param name The name of the WebVRFreeCamera
  91990. * @param position The starting anchor position for the camera
  91991. * @param scene The scene the camera belongs to
  91992. * @param webVROptions a set of customizable options for the webVRCamera
  91993. */
  91994. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91995. if (webVROptions === void 0) { webVROptions = {}; }
  91996. var _this = _super.call(this, name, position, scene) || this;
  91997. _this.webVROptions = webVROptions;
  91998. /**
  91999. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  92000. */
  92001. _this._vrDevice = null;
  92002. /**
  92003. * The rawPose of the vrDevice.
  92004. */
  92005. _this.rawPose = null;
  92006. _this._specsVersion = "1.1";
  92007. _this._attached = false;
  92008. _this._descendants = [];
  92009. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  92010. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  92011. /** @hidden */
  92012. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  92013. _this._standingMatrix = null;
  92014. /**
  92015. * Represents device position in babylon space.
  92016. */
  92017. _this.devicePosition = BABYLON.Vector3.Zero();
  92018. /**
  92019. * Represents device rotation in babylon space.
  92020. */
  92021. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  92022. /**
  92023. * The scale of the device to be used when translating from device space to babylon space.
  92024. */
  92025. _this.deviceScaleFactor = 1;
  92026. _this._deviceToWorld = BABYLON.Matrix.Identity();
  92027. _this._worldToDevice = BABYLON.Matrix.Identity();
  92028. /**
  92029. * References to the webVR controllers for the vrDevice.
  92030. */
  92031. _this.controllers = [];
  92032. /**
  92033. * Emits an event when a controller is attached.
  92034. */
  92035. _this.onControllersAttachedObservable = new BABYLON.Observable();
  92036. /**
  92037. * Emits an event when a controller's mesh has been loaded;
  92038. */
  92039. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92040. /**
  92041. * Emits an event when the HMD's pose has been updated.
  92042. */
  92043. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  92044. _this._poseSet = false;
  92045. /**
  92046. * If the rig cameras be used as parent instead of this camera.
  92047. */
  92048. _this.rigParenting = true;
  92049. _this._defaultHeight = undefined;
  92050. _this._workingVector = BABYLON.Vector3.Zero();
  92051. _this._oneVector = BABYLON.Vector3.One();
  92052. _this._workingMatrix = BABYLON.Matrix.Identity();
  92053. _this._cache.position = BABYLON.Vector3.Zero();
  92054. if (webVROptions.defaultHeight) {
  92055. _this._defaultHeight = webVROptions.defaultHeight;
  92056. _this.position.y = _this._defaultHeight;
  92057. }
  92058. _this.minZ = 0.1;
  92059. //legacy support - the compensation boolean was removed.
  92060. if (arguments.length === 5) {
  92061. _this.webVROptions = arguments[4];
  92062. }
  92063. // default webVR options
  92064. if (_this.webVROptions.trackPosition == undefined) {
  92065. _this.webVROptions.trackPosition = true;
  92066. }
  92067. if (_this.webVROptions.controllerMeshes == undefined) {
  92068. _this.webVROptions.controllerMeshes = true;
  92069. }
  92070. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  92071. _this.webVROptions.defaultLightingOnControllers = true;
  92072. }
  92073. _this.rotationQuaternion = new BABYLON.Quaternion();
  92074. if (_this.webVROptions && _this.webVROptions.positionScale) {
  92075. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  92076. }
  92077. //enable VR
  92078. var engine = _this.getEngine();
  92079. _this._onVREnabled = function (success) { if (success) {
  92080. _this.initControllers();
  92081. } };
  92082. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  92083. engine.initWebVR().add(function (event) {
  92084. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  92085. return;
  92086. }
  92087. _this._vrDevice = event.vrDisplay;
  92088. //reset the rig parameters.
  92089. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  92090. if (_this._attached) {
  92091. _this.getEngine().enableVR();
  92092. }
  92093. });
  92094. if (typeof (VRFrameData) !== "undefined")
  92095. _this._frameData = new VRFrameData();
  92096. /**
  92097. * The idea behind the following lines:
  92098. * objects that have the camera as parent should actually have the rig cameras as a parent.
  92099. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  92100. * the second will not show it correctly.
  92101. *
  92102. * To solve this - each object that has the camera as parent will be added to a protected array.
  92103. * When the rig camera renders, it will take this array and set all of those to be its children.
  92104. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  92105. * Amazing!
  92106. */
  92107. scene.onBeforeCameraRenderObservable.add(function (camera) {
  92108. if (camera.parent === _this && _this.rigParenting) {
  92109. _this._descendants = _this.getDescendants(true, function (n) {
  92110. // don't take the cameras or the controllers!
  92111. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  92112. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  92113. return !isController && !isRigCamera;
  92114. });
  92115. _this._descendants.forEach(function (node) {
  92116. node.parent = camera;
  92117. });
  92118. }
  92119. });
  92120. scene.onAfterCameraRenderObservable.add(function (camera) {
  92121. if (camera.parent === _this && _this.rigParenting) {
  92122. _this._descendants.forEach(function (node) {
  92123. node.parent = _this;
  92124. });
  92125. }
  92126. });
  92127. return _this;
  92128. }
  92129. /**
  92130. * Gets the device distance from the ground in meters.
  92131. * @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.
  92132. */
  92133. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  92134. if (this._standingMatrix) {
  92135. // Add standing matrix offset to get real offset from ground in room
  92136. this._standingMatrix.getTranslationToRef(this._workingVector);
  92137. return this._deviceRoomPosition.y + this._workingVector.y;
  92138. }
  92139. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  92140. return this._defaultHeight || 0;
  92141. };
  92142. /**
  92143. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92144. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  92145. */
  92146. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  92147. var _this = this;
  92148. if (callback === void 0) { callback = function (bool) { }; }
  92149. // Use standing matrix if available
  92150. this.getEngine().initWebVRAsync().then(function (result) {
  92151. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  92152. callback(false);
  92153. }
  92154. else {
  92155. _this._standingMatrix = new BABYLON.Matrix();
  92156. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  92157. if (!_this.getScene().useRightHandedSystem) {
  92158. [2, 6, 8, 9, 14].forEach(function (num) {
  92159. if (_this._standingMatrix) {
  92160. _this._standingMatrix.m[num] *= -1;
  92161. }
  92162. });
  92163. }
  92164. callback(true);
  92165. }
  92166. });
  92167. };
  92168. /**
  92169. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92170. * @returns A promise with a boolean set to if the standing matrix is supported.
  92171. */
  92172. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  92173. var _this = this;
  92174. return new Promise(function (res, rej) {
  92175. _this.useStandingMatrix(function (supported) {
  92176. res(supported);
  92177. });
  92178. });
  92179. };
  92180. /**
  92181. * Disposes the camera
  92182. */
  92183. WebVRFreeCamera.prototype.dispose = function () {
  92184. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  92185. _super.prototype.dispose.call(this);
  92186. };
  92187. /**
  92188. * Gets a vrController by name.
  92189. * @param name The name of the controller to retreive
  92190. * @returns the controller matching the name specified or null if not found
  92191. */
  92192. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  92193. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  92194. var gp = _a[_i];
  92195. if (gp.hand === name) {
  92196. return gp;
  92197. }
  92198. }
  92199. return null;
  92200. };
  92201. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92202. /**
  92203. * The controller corrisponding to the users left hand.
  92204. */
  92205. get: function () {
  92206. if (!this._leftController) {
  92207. this._leftController = this.getControllerByName("left");
  92208. }
  92209. return this._leftController;
  92210. },
  92211. enumerable: true,
  92212. configurable: true
  92213. });
  92214. ;
  92215. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92216. /**
  92217. * The controller corrisponding to the users right hand.
  92218. */
  92219. get: function () {
  92220. if (!this._rightController) {
  92221. this._rightController = this.getControllerByName("right");
  92222. }
  92223. return this._rightController;
  92224. },
  92225. enumerable: true,
  92226. configurable: true
  92227. });
  92228. ;
  92229. /**
  92230. * Casts a ray forward from the vrCamera's gaze.
  92231. * @param length Length of the ray (default: 100)
  92232. * @returns the ray corrisponding to the gaze
  92233. */
  92234. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92235. if (length === void 0) { length = 100; }
  92236. if (this.leftCamera) {
  92237. // Use left eye to avoid computation to compute center on every call
  92238. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92239. }
  92240. else {
  92241. return _super.prototype.getForwardRay.call(this, length);
  92242. }
  92243. };
  92244. /**
  92245. * Updates the camera based on device's frame data
  92246. */
  92247. WebVRFreeCamera.prototype._checkInputs = function () {
  92248. if (this._vrDevice && this._vrDevice.isPresenting) {
  92249. this._vrDevice.getFrameData(this._frameData);
  92250. this.updateFromDevice(this._frameData.pose);
  92251. }
  92252. _super.prototype._checkInputs.call(this);
  92253. };
  92254. /**
  92255. * Updates the poseControlled values based on the input device pose.
  92256. * @param poseData Pose coming from the device
  92257. */
  92258. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92259. if (poseData && poseData.orientation) {
  92260. this.rawPose = poseData;
  92261. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92262. if (this.getScene().useRightHandedSystem) {
  92263. this._deviceRoomRotationQuaternion.z *= -1;
  92264. this._deviceRoomRotationQuaternion.w *= -1;
  92265. }
  92266. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92267. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92268. if (this.getScene().useRightHandedSystem) {
  92269. this._deviceRoomPosition.z *= -1;
  92270. }
  92271. }
  92272. this._poseSet = true;
  92273. }
  92274. };
  92275. /**
  92276. * WebVR's attach control will start broadcasting frames to the device.
  92277. * Note that in certain browsers (chrome for example) this function must be called
  92278. * within a user-interaction callback. Example:
  92279. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92280. *
  92281. * @param element html element to attach the vrDevice to
  92282. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92283. */
  92284. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92285. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92286. this._attached = true;
  92287. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92288. if (this._vrDevice) {
  92289. this.getEngine().enableVR();
  92290. }
  92291. };
  92292. /**
  92293. * Detaches the camera from the html element and disables VR
  92294. *
  92295. * @param element html element to detach from
  92296. */
  92297. WebVRFreeCamera.prototype.detachControl = function (element) {
  92298. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92299. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92300. _super.prototype.detachControl.call(this, element);
  92301. this._attached = false;
  92302. this.getEngine().disableVR();
  92303. };
  92304. /**
  92305. * @returns the name of this class
  92306. */
  92307. WebVRFreeCamera.prototype.getClassName = function () {
  92308. return "WebVRFreeCamera";
  92309. };
  92310. /**
  92311. * Calls resetPose on the vrDisplay
  92312. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92313. */
  92314. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92315. //uses the vrDisplay's "resetPose()".
  92316. //pitch and roll won't be affected.
  92317. this._vrDevice.resetPose();
  92318. };
  92319. /**
  92320. * Updates the rig cameras (left and right eye)
  92321. */
  92322. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92323. var camLeft = this._rigCameras[0];
  92324. var camRight = this._rigCameras[1];
  92325. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92326. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92327. camLeft.position.copyFrom(this._deviceRoomPosition);
  92328. camRight.position.copyFrom(this._deviceRoomPosition);
  92329. };
  92330. /**
  92331. * Updates the cached values of the camera
  92332. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92333. */
  92334. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92335. var _this = this;
  92336. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92337. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92338. if (!this.updateCacheCalled) {
  92339. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92340. this.updateCacheCalled = true;
  92341. this.update();
  92342. }
  92343. // Set working vector to the device position in room space rotated by the new rotation
  92344. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92345. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92346. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92347. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92348. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92349. // Add translation from anchor position
  92350. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92351. this._workingVector.addInPlace(this.position);
  92352. this._workingVector.subtractInPlace(this._cache.position);
  92353. this._deviceToWorld.setTranslation(this._workingVector);
  92354. // Set an inverted matrix to be used when updating the camera
  92355. this._deviceToWorld.invertToRef(this._worldToDevice);
  92356. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92357. this.controllers.forEach(function (controller) {
  92358. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92359. controller.update();
  92360. });
  92361. }
  92362. if (!ignoreParentClass) {
  92363. _super.prototype._updateCache.call(this);
  92364. }
  92365. this.updateCacheCalled = false;
  92366. };
  92367. /**
  92368. * Updates the current device position and rotation in the babylon world
  92369. */
  92370. WebVRFreeCamera.prototype.update = function () {
  92371. // Get current device position in babylon world
  92372. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92373. // Get current device rotation in babylon world
  92374. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92375. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92376. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92377. if (this._poseSet) {
  92378. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92379. }
  92380. _super.prototype.update.call(this);
  92381. };
  92382. /**
  92383. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92384. * @returns an identity matrix
  92385. */
  92386. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92387. return BABYLON.Matrix.Identity();
  92388. };
  92389. /**
  92390. * This function is called by the two RIG cameras.
  92391. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92392. */
  92393. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92394. var _this = this;
  92395. // Update the parent camera prior to using a child camera to avoid desynchronization
  92396. var parentCamera = this._cameraRigParams["parentCamera"];
  92397. parentCamera._updateCache();
  92398. //WebVR 1.1
  92399. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92400. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92401. if (!this.getScene().useRightHandedSystem) {
  92402. [2, 6, 8, 9, 14].forEach(function (num) {
  92403. _this._webvrViewMatrix.m[num] *= -1;
  92404. });
  92405. }
  92406. // update the camera rotation matrix
  92407. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92408. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92409. // Computing target and final matrix
  92410. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92411. // should the view matrix be updated with scale and position offset?
  92412. if (parentCamera.deviceScaleFactor !== 1) {
  92413. this._webvrViewMatrix.invert();
  92414. // scale the position, if set
  92415. if (parentCamera.deviceScaleFactor) {
  92416. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92417. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92418. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92419. }
  92420. this._webvrViewMatrix.invert();
  92421. }
  92422. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92423. // Compute global position
  92424. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92425. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92426. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92427. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92428. this._markSyncedWithParent();
  92429. return this._webvrViewMatrix;
  92430. };
  92431. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92432. var _this = this;
  92433. var parentCamera = this.parent;
  92434. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92435. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92436. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92437. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92438. //babylon compatible matrix
  92439. if (!this.getScene().useRightHandedSystem) {
  92440. [8, 9, 10, 11].forEach(function (num) {
  92441. _this._projectionMatrix.m[num] *= -1;
  92442. });
  92443. }
  92444. return this._projectionMatrix;
  92445. };
  92446. /**
  92447. * Initializes the controllers and their meshes
  92448. */
  92449. WebVRFreeCamera.prototype.initControllers = function () {
  92450. var _this = this;
  92451. this.controllers = [];
  92452. var manager = this.getScene().gamepadManager;
  92453. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92454. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92455. var webVrController = gamepad;
  92456. if (webVrController.defaultModel) {
  92457. webVrController.defaultModel.setEnabled(false);
  92458. }
  92459. if (webVrController.hand === "right") {
  92460. _this._rightController = null;
  92461. }
  92462. if (webVrController.hand === "left") {
  92463. _this._leftController = null;
  92464. }
  92465. var controllerIndex = _this.controllers.indexOf(webVrController);
  92466. if (controllerIndex !== -1) {
  92467. _this.controllers.splice(controllerIndex, 1);
  92468. }
  92469. }
  92470. });
  92471. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92472. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92473. var webVrController_1 = gamepad;
  92474. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92475. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92476. if (_this.webVROptions.controllerMeshes) {
  92477. if (webVrController_1.defaultModel) {
  92478. webVrController_1.defaultModel.setEnabled(true);
  92479. }
  92480. else {
  92481. // Load the meshes
  92482. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92483. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92484. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92485. if (_this.webVROptions.defaultLightingOnControllers) {
  92486. if (!_this._lightOnControllers) {
  92487. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92488. }
  92489. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92490. var children = mesh.getChildren();
  92491. if (children.length !== 0) {
  92492. children.forEach(function (mesh) {
  92493. light.includedOnlyMeshes.push(mesh);
  92494. activateLightOnSubMeshes_1(mesh, light);
  92495. });
  92496. }
  92497. };
  92498. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92499. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92500. }
  92501. });
  92502. }
  92503. }
  92504. webVrController_1.attachToPoseControlledCamera(_this);
  92505. // since this is async - sanity check. Is the controller already stored?
  92506. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92507. //add to the controllers array
  92508. _this.controllers.push(webVrController_1);
  92509. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92510. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92511. // So we're overriding setting left & right manually to be sure
  92512. var firstViveWandDetected = false;
  92513. for (var i = 0; i < _this.controllers.length; i++) {
  92514. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92515. if (!firstViveWandDetected) {
  92516. firstViveWandDetected = true;
  92517. _this.controllers[i].hand = "left";
  92518. }
  92519. else {
  92520. _this.controllers[i].hand = "right";
  92521. }
  92522. }
  92523. }
  92524. //did we find enough controllers? Great! let the developer know.
  92525. if (_this.controllers.length >= 2) {
  92526. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  92527. }
  92528. }
  92529. }
  92530. });
  92531. };
  92532. return WebVRFreeCamera;
  92533. }(BABYLON.FreeCamera));
  92534. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  92535. })(BABYLON || (BABYLON = {}));
  92536. //# sourceMappingURL=babylon.webVRCamera.js.map
  92537. var BABYLON;
  92538. (function (BABYLON) {
  92539. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  92540. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  92541. });
  92542. // We're mainly based on the logic defined into the FreeCamera code
  92543. /**
  92544. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  92545. * being tilted forward or back and left or right.
  92546. */
  92547. var DeviceOrientationCamera = /** @class */ (function (_super) {
  92548. __extends(DeviceOrientationCamera, _super);
  92549. /**
  92550. * Creates a new device orientation camera
  92551. * @param name The name of the camera
  92552. * @param position The start position camera
  92553. * @param scene The scene the camera belongs to
  92554. */
  92555. function DeviceOrientationCamera(name, position, scene) {
  92556. var _this = _super.call(this, name, position, scene) || this;
  92557. _this._quaternionCache = new BABYLON.Quaternion();
  92558. _this.inputs.addDeviceOrientation();
  92559. return _this;
  92560. }
  92561. /**
  92562. * Gets the current instance class name ("DeviceOrientationCamera").
  92563. * This helps avoiding instanceof at run time.
  92564. * @returns the class name
  92565. */
  92566. DeviceOrientationCamera.prototype.getClassName = function () {
  92567. return "DeviceOrientationCamera";
  92568. };
  92569. /**
  92570. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  92571. */
  92572. DeviceOrientationCamera.prototype._checkInputs = function () {
  92573. _super.prototype._checkInputs.call(this);
  92574. this._quaternionCache.copyFrom(this.rotationQuaternion);
  92575. if (this._initialQuaternion) {
  92576. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92577. }
  92578. };
  92579. /**
  92580. * Reset the camera to its default orientation on the specified axis only.
  92581. * @param axis The axis to reset
  92582. */
  92583. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  92584. var _this = this;
  92585. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  92586. //can only work if this camera has a rotation quaternion already.
  92587. if (!this.rotationQuaternion)
  92588. return;
  92589. if (!this._initialQuaternion) {
  92590. this._initialQuaternion = new BABYLON.Quaternion();
  92591. }
  92592. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  92593. ['x', 'y', 'z'].forEach(function (axisName) {
  92594. if (!axis[axisName]) {
  92595. _this._initialQuaternion[axisName] = 0;
  92596. }
  92597. else {
  92598. _this._initialQuaternion[axisName] *= -1;
  92599. }
  92600. });
  92601. this._initialQuaternion.normalize();
  92602. //force rotation update
  92603. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92604. };
  92605. return DeviceOrientationCamera;
  92606. }(BABYLON.FreeCamera));
  92607. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92608. })(BABYLON || (BABYLON = {}));
  92609. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92610. var BABYLON;
  92611. (function (BABYLON) {
  92612. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92613. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92614. });
  92615. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92616. __extends(VRDeviceOrientationFreeCamera, _super);
  92617. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92618. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92619. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92620. var _this = _super.call(this, name, position, scene) || this;
  92621. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92622. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92623. return _this;
  92624. }
  92625. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92626. return "VRDeviceOrientationFreeCamera";
  92627. };
  92628. return VRDeviceOrientationFreeCamera;
  92629. }(BABYLON.DeviceOrientationCamera));
  92630. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92631. })(BABYLON || (BABYLON = {}));
  92632. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  92633. var BABYLON;
  92634. (function (BABYLON) {
  92635. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92636. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  92637. });
  92638. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92639. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92640. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92641. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92642. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92643. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92644. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92645. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92646. _this.inputs.addVRDeviceOrientation();
  92647. return _this;
  92648. }
  92649. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92650. return "VRDeviceOrientationArcRotateCamera";
  92651. };
  92652. return VRDeviceOrientationArcRotateCamera;
  92653. }(BABYLON.ArcRotateCamera));
  92654. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92655. })(BABYLON || (BABYLON = {}));
  92656. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  92657. var BABYLON;
  92658. (function (BABYLON) {
  92659. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  92660. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  92661. });
  92662. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92663. __extends(VRDeviceOrientationGamepadCamera, _super);
  92664. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92665. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92666. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92667. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92668. _this.inputs.addGamepad();
  92669. return _this;
  92670. }
  92671. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92672. return "VRDeviceOrientationGamepadCamera";
  92673. };
  92674. return VRDeviceOrientationGamepadCamera;
  92675. }(BABYLON.VRDeviceOrientationFreeCamera));
  92676. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92677. })(BABYLON || (BABYLON = {}));
  92678. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  92679. var BABYLON;
  92680. (function (BABYLON) {
  92681. var VRExperienceHelperGazer = /** @class */ (function () {
  92682. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92683. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92684. this.scene = scene;
  92685. this._pointerDownOnMeshAsked = false;
  92686. this._isActionableMesh = false;
  92687. this._teleportationRequestInitiated = false;
  92688. this._teleportationBackRequestInitiated = false;
  92689. this._rotationRightAsked = false;
  92690. this._rotationLeftAsked = false;
  92691. this._dpadPressed = true;
  92692. this._activePointer = false;
  92693. this._id = VRExperienceHelperGazer._idCounter++;
  92694. // Gaze tracker
  92695. if (!gazeTrackerToClone) {
  92696. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92697. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92698. this._gazeTracker.isPickable = false;
  92699. this._gazeTracker.isVisible = false;
  92700. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92701. targetMat.specularColor = BABYLON.Color3.Black();
  92702. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92703. targetMat.backFaceCulling = false;
  92704. this._gazeTracker.material = targetMat;
  92705. }
  92706. else {
  92707. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92708. }
  92709. }
  92710. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92711. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92712. };
  92713. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92714. this._pointerDownOnMeshAsked = true;
  92715. if (this._currentHit) {
  92716. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92717. }
  92718. };
  92719. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92720. if (this._currentHit) {
  92721. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92722. }
  92723. this._pointerDownOnMeshAsked = false;
  92724. };
  92725. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92726. this._activePointer = true;
  92727. };
  92728. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92729. this._activePointer = false;
  92730. };
  92731. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92732. if (distance === void 0) { distance = 100; }
  92733. };
  92734. VRExperienceHelperGazer.prototype.dispose = function () {
  92735. this._interactionsEnabled = false;
  92736. this._teleportationEnabled = false;
  92737. if (this._gazeTracker) {
  92738. this._gazeTracker.dispose();
  92739. }
  92740. };
  92741. VRExperienceHelperGazer._idCounter = 0;
  92742. return VRExperienceHelperGazer;
  92743. }());
  92744. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92745. __extends(VRExperienceHelperControllerGazer, _super);
  92746. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92747. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92748. _this.webVRController = webVRController;
  92749. // Laser pointer
  92750. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92751. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92752. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92753. laserPointerMaterial.alpha = 0.6;
  92754. _this._laserPointer.material = laserPointerMaterial;
  92755. _this._laserPointer.rotation.x = Math.PI / 2;
  92756. _this._laserPointer.position.z = -0.5;
  92757. _this._laserPointer.isVisible = false;
  92758. _this._laserPointer.isPickable = false;
  92759. if (!webVRController.mesh) {
  92760. // Create an empty mesh that is used prior to loading the high quality model
  92761. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92762. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92763. preloadPointerPose.rotation.x = -0.7;
  92764. preloadMesh.addChild(preloadPointerPose);
  92765. webVRController.attachToMesh(preloadMesh);
  92766. }
  92767. _this._setLaserPointerParent(webVRController.mesh);
  92768. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92769. _this._setLaserPointerParent(mesh);
  92770. });
  92771. return _this;
  92772. }
  92773. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92774. return this.webVRController.getForwardRay(length);
  92775. };
  92776. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92777. _super.prototype._activatePointer.call(this);
  92778. this._laserPointer.isVisible = true;
  92779. };
  92780. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92781. _super.prototype._deactivatePointer.call(this);
  92782. this._laserPointer.isVisible = false;
  92783. };
  92784. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92785. this._laserPointer.material.emissiveColor = color;
  92786. };
  92787. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92788. var makeNotPick = function (root) {
  92789. root.isPickable = false;
  92790. root.getChildMeshes().forEach(function (c) {
  92791. makeNotPick(c);
  92792. });
  92793. };
  92794. makeNotPick(mesh);
  92795. var childMeshes = mesh.getChildMeshes();
  92796. this.webVRController._pointingPoseNode = null;
  92797. for (var i = 0; i < childMeshes.length; i++) {
  92798. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92799. mesh = childMeshes[i];
  92800. this.webVRController._pointingPoseNode = mesh;
  92801. break;
  92802. }
  92803. }
  92804. this._laserPointer.parent = mesh;
  92805. };
  92806. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92807. if (distance === void 0) { distance = 100; }
  92808. this._laserPointer.scaling.y = distance;
  92809. this._laserPointer.position.z = -distance / 2;
  92810. };
  92811. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92812. _super.prototype.dispose.call(this);
  92813. this._laserPointer.dispose();
  92814. if (this._meshAttachedObserver) {
  92815. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92816. }
  92817. };
  92818. return VRExperienceHelperControllerGazer;
  92819. }(VRExperienceHelperGazer));
  92820. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92821. __extends(VRExperienceHelperCameraGazer, _super);
  92822. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92823. var _this = _super.call(this, scene) || this;
  92824. _this.getCamera = getCamera;
  92825. return _this;
  92826. }
  92827. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92828. var camera = this.getCamera();
  92829. if (camera) {
  92830. return camera.getForwardRay(length);
  92831. }
  92832. else {
  92833. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92834. }
  92835. };
  92836. return VRExperienceHelperCameraGazer;
  92837. }(VRExperienceHelperGazer));
  92838. /**
  92839. * Helps to quickly add VR support to an existing scene.
  92840. * See http://doc.babylonjs.com/how_to/webvr_helper
  92841. */
  92842. var VRExperienceHelper = /** @class */ (function () {
  92843. /**
  92844. * Instantiates a VRExperienceHelper.
  92845. * Helps to quickly add VR support to an existing scene.
  92846. * @param scene The scene the VRExperienceHelper belongs to.
  92847. * @param webVROptions Options to modify the vr experience helper's behavior.
  92848. */
  92849. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92850. if (webVROptions === void 0) { webVROptions = {}; }
  92851. var _this = this;
  92852. this.webVROptions = webVROptions;
  92853. // Can the system support WebVR, even if a headset isn't plugged in?
  92854. this._webVRsupported = false;
  92855. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92856. this._webVRready = false;
  92857. // Are we waiting for the requestPresent callback to complete?
  92858. this._webVRrequesting = false;
  92859. // Are we presenting to the headset right now?
  92860. this._webVRpresenting = false;
  92861. // Are we presenting in the fullscreen fallback?
  92862. this._fullscreenVRpresenting = false;
  92863. /**
  92864. * Observable raised when entering VR.
  92865. */
  92866. this.onEnteringVRObservable = new BABYLON.Observable();
  92867. /**
  92868. * Observable raised when exiting VR.
  92869. */
  92870. this.onExitingVRObservable = new BABYLON.Observable();
  92871. /**
  92872. * Observable raised when controller mesh is loaded.
  92873. */
  92874. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92875. this._useCustomVRButton = false;
  92876. this._teleportationRequested = false;
  92877. this._teleportActive = false;
  92878. this._floorMeshesCollection = [];
  92879. this._rotationAllowed = true;
  92880. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92881. this._isDefaultTeleportationTarget = true;
  92882. this._teleportationFillColor = "#444444";
  92883. this._teleportationBorderColor = "#FFFFFF";
  92884. this._rotationAngle = 0;
  92885. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92886. this._padSensibilityUp = 0.65;
  92887. this._padSensibilityDown = 0.35;
  92888. this.leftController = null;
  92889. this.rightController = null;
  92890. /**
  92891. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92892. */
  92893. this.onNewMeshSelected = new BABYLON.Observable();
  92894. /**
  92895. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92896. */
  92897. this.onNewMeshPicked = new BABYLON.Observable();
  92898. /**
  92899. * Observable raised before camera teleportation
  92900. */
  92901. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92902. /**
  92903. * Observable raised after camera teleportation
  92904. */
  92905. this.onAfterCameraTeleport = new BABYLON.Observable();
  92906. /**
  92907. * Observable raised when current selected mesh gets unselected
  92908. */
  92909. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92910. /**
  92911. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92912. */
  92913. this.teleportationEnabled = true;
  92914. this._teleportationInitialized = false;
  92915. this._interactionsEnabled = false;
  92916. this._interactionsRequested = false;
  92917. this._displayGaze = true;
  92918. this._displayLaserPointer = true;
  92919. this._onResize = function () {
  92920. _this.moveButtonToBottomRight();
  92921. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92922. _this.exitVR();
  92923. }
  92924. };
  92925. this._onFullscreenChange = function () {
  92926. if (document.fullscreen !== undefined) {
  92927. _this._fullscreenVRpresenting = document.fullscreen;
  92928. }
  92929. else if (document.mozFullScreen !== undefined) {
  92930. _this._fullscreenVRpresenting = document.mozFullScreen;
  92931. }
  92932. else if (document.webkitIsFullScreen !== undefined) {
  92933. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92934. }
  92935. else if (document.msIsFullScreen !== undefined) {
  92936. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92937. }
  92938. else if (document.msFullscreenElement !== undefined) {
  92939. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92940. }
  92941. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92942. _this.exitVR();
  92943. if (!_this._useCustomVRButton) {
  92944. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92945. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92946. }
  92947. }
  92948. };
  92949. this.beforeRender = function () {
  92950. if (_this.leftController && _this.leftController._activePointer) {
  92951. _this._castRayAndSelectObject(_this.leftController);
  92952. }
  92953. if (_this.rightController && _this.rightController._activePointer) {
  92954. _this._castRayAndSelectObject(_this.rightController);
  92955. }
  92956. if (_this._noControllerIsActive) {
  92957. _this._castRayAndSelectObject(_this._cameraGazer);
  92958. }
  92959. else {
  92960. _this._cameraGazer._gazeTracker.isVisible = false;
  92961. }
  92962. };
  92963. this._onNewGamepadConnected = function (gamepad) {
  92964. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92965. if (gamepad.leftStick) {
  92966. gamepad.onleftstickchanged(function (stickValues) {
  92967. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92968. // Listening to classic/xbox gamepad only if no VR controller is active
  92969. if ((!_this.leftController && !_this.rightController) ||
  92970. ((_this.leftController && !_this.leftController._activePointer) &&
  92971. (_this.rightController && !_this.rightController._activePointer))) {
  92972. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92973. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92974. }
  92975. }
  92976. });
  92977. }
  92978. if (gamepad.rightStick) {
  92979. gamepad.onrightstickchanged(function (stickValues) {
  92980. if (_this._teleportationInitialized) {
  92981. _this._checkRotate(stickValues, _this._cameraGazer);
  92982. }
  92983. });
  92984. }
  92985. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92986. gamepad.onbuttondown(function (buttonPressed) {
  92987. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92988. _this._cameraGazer._selectionPointerDown();
  92989. }
  92990. });
  92991. gamepad.onbuttonup(function (buttonPressed) {
  92992. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92993. _this._cameraGazer._selectionPointerUp();
  92994. }
  92995. });
  92996. }
  92997. }
  92998. else {
  92999. var webVRController = gamepad;
  93000. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  93001. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  93002. _this.rightController = controller;
  93003. }
  93004. else {
  93005. _this.leftController = controller;
  93006. }
  93007. _this._tryEnableInteractionOnController(controller);
  93008. }
  93009. };
  93010. // 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
  93011. this._tryEnableInteractionOnController = function (controller) {
  93012. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  93013. _this._enableInteractionOnController(controller);
  93014. }
  93015. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  93016. _this._enableTeleportationOnController(controller);
  93017. }
  93018. };
  93019. this._onNewGamepadDisconnected = function (gamepad) {
  93020. if (gamepad instanceof BABYLON.WebVRController) {
  93021. if (gamepad.hand === "left" && _this.leftController != null) {
  93022. _this.leftController.dispose();
  93023. _this.leftController = null;
  93024. }
  93025. if (gamepad.hand === "right" && _this.rightController != null) {
  93026. _this.rightController.dispose();
  93027. _this.rightController = null;
  93028. }
  93029. }
  93030. };
  93031. this._workingVector = BABYLON.Vector3.Zero();
  93032. this._workingQuaternion = BABYLON.Quaternion.Identity();
  93033. this._workingMatrix = BABYLON.Matrix.Identity();
  93034. this._scene = scene;
  93035. this._canvas = scene.getEngine().getRenderingCanvas();
  93036. // Parse options
  93037. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  93038. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  93039. }
  93040. if (webVROptions.createDeviceOrientationCamera === undefined) {
  93041. webVROptions.createDeviceOrientationCamera = true;
  93042. }
  93043. if (webVROptions.laserToggle === undefined) {
  93044. webVROptions.laserToggle = true;
  93045. }
  93046. if (webVROptions.defaultHeight === undefined) {
  93047. webVROptions.defaultHeight = 1.7;
  93048. }
  93049. if (webVROptions.useCustomVRButton) {
  93050. this._useCustomVRButton = true;
  93051. if (webVROptions.customVRButton) {
  93052. this._btnVR = webVROptions.customVRButton;
  93053. }
  93054. }
  93055. if (webVROptions.rayLength) {
  93056. this._rayLength = webVROptions.rayLength;
  93057. }
  93058. this._defaultHeight = webVROptions.defaultHeight;
  93059. if (webVROptions.positionScale) {
  93060. this._rayLength *= webVROptions.positionScale;
  93061. this._defaultHeight *= webVROptions.positionScale;
  93062. }
  93063. // Set position
  93064. if (this._scene.activeCamera) {
  93065. this._position = this._scene.activeCamera.position.clone();
  93066. }
  93067. else {
  93068. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  93069. }
  93070. // Set non-vr camera
  93071. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  93072. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  93073. // Copy data from existing camera
  93074. if (this._scene.activeCamera) {
  93075. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93076. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  93077. // Set rotation from previous camera
  93078. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  93079. var targetCamera = this._scene.activeCamera;
  93080. if (targetCamera.rotationQuaternion) {
  93081. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  93082. }
  93083. else {
  93084. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  93085. }
  93086. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  93087. }
  93088. }
  93089. this._scene.activeCamera = this._deviceOrientationCamera;
  93090. if (this._canvas) {
  93091. this._scene.activeCamera.attachControl(this._canvas);
  93092. }
  93093. }
  93094. else {
  93095. this._existingCamera = this._scene.activeCamera;
  93096. }
  93097. // Create VR cameras
  93098. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93099. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  93100. }
  93101. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  93102. this._webVRCamera.useStandingMatrix();
  93103. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  93104. // Create default button
  93105. if (!this._useCustomVRButton) {
  93106. this._btnVR = document.createElement("BUTTON");
  93107. this._btnVR.className = "babylonVRicon";
  93108. this._btnVR.id = "babylonVRiconbtn";
  93109. this._btnVR.title = "Click to switch to VR";
  93110. 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) }";
  93111. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  93112. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  93113. // css += ".babylonVRicon.vrdisplaysupported { }";
  93114. // css += ".babylonVRicon.vrdisplayready { }";
  93115. // css += ".babylonVRicon.vrdisplayrequesting { }";
  93116. var style = document.createElement('style');
  93117. style.appendChild(document.createTextNode(css));
  93118. document.getElementsByTagName('head')[0].appendChild(style);
  93119. this.moveButtonToBottomRight();
  93120. }
  93121. // VR button click event
  93122. if (this._btnVR) {
  93123. this._btnVR.addEventListener("click", function () {
  93124. if (!_this.isInVRMode) {
  93125. _this.enterVR();
  93126. }
  93127. else {
  93128. _this.exitVR();
  93129. }
  93130. });
  93131. }
  93132. // Window events
  93133. window.addEventListener("resize", this._onResize);
  93134. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  93135. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  93136. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  93137. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  93138. document.onmsfullscreenchange = this._onFullscreenChange;
  93139. // Display vr button when headset is connected
  93140. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93141. this.displayVRButton();
  93142. }
  93143. else {
  93144. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  93145. if (e.vrDisplay) {
  93146. _this.displayVRButton();
  93147. }
  93148. });
  93149. }
  93150. // Exiting VR mode using 'ESC' key on desktop
  93151. this._onKeyDown = function (event) {
  93152. if (event.keyCode === 27 && _this.isInVRMode) {
  93153. _this.exitVR();
  93154. }
  93155. };
  93156. document.addEventListener("keydown", this._onKeyDown);
  93157. // Exiting VR mode double tapping the touch screen
  93158. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  93159. if (_this.isInVRMode) {
  93160. _this.exitVR();
  93161. if (_this._fullscreenVRpresenting) {
  93162. _this._scene.getEngine().switchFullscreen(true);
  93163. }
  93164. }
  93165. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  93166. // Listen for WebVR display changes
  93167. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  93168. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  93169. this._onVRRequestPresentStart = function () {
  93170. _this._webVRrequesting = true;
  93171. _this.updateButtonVisibility();
  93172. };
  93173. this._onVRRequestPresentComplete = function (success) {
  93174. _this._webVRrequesting = false;
  93175. _this.updateButtonVisibility();
  93176. };
  93177. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  93178. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  93179. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  93180. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93181. scene.onDisposeObservable.add(function () {
  93182. _this.dispose();
  93183. });
  93184. // Gamepad connection events
  93185. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  93186. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  93187. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  93188. this.updateButtonVisibility();
  93189. //create easing functions
  93190. this._circleEase = new BABYLON.CircleEase();
  93191. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93192. if (this.webVROptions.floorMeshes) {
  93193. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  93194. }
  93195. }
  93196. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  93197. /** Return this.onEnteringVRObservable
  93198. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93199. */
  93200. get: function () {
  93201. return this.onEnteringVRObservable;
  93202. },
  93203. enumerable: true,
  93204. configurable: true
  93205. });
  93206. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93207. /** Return this.onExitingVRObservable
  93208. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93209. */
  93210. get: function () {
  93211. return this.onExitingVRObservable;
  93212. },
  93213. enumerable: true,
  93214. configurable: true
  93215. });
  93216. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93217. /** Return this.onControllerMeshLoadedObservable
  93218. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93219. */
  93220. get: function () {
  93221. return this.onControllerMeshLoadedObservable;
  93222. },
  93223. enumerable: true,
  93224. configurable: true
  93225. });
  93226. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93227. /**
  93228. * The mesh used to display where the user is going to teleport.
  93229. */
  93230. get: function () {
  93231. return this._teleportationTarget;
  93232. },
  93233. /**
  93234. * Sets the mesh to be used to display where the user is going to teleport.
  93235. */
  93236. set: function (value) {
  93237. if (value) {
  93238. value.name = "teleportationTarget";
  93239. this._isDefaultTeleportationTarget = false;
  93240. this._teleportationTarget = value;
  93241. }
  93242. },
  93243. enumerable: true,
  93244. configurable: true
  93245. });
  93246. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93247. /**
  93248. * The mesh used to display where the user is selecting,
  93249. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93250. * See http://doc.babylonjs.com/resources/baking_transformations
  93251. */
  93252. get: function () {
  93253. return this._cameraGazer._gazeTracker;
  93254. },
  93255. set: function (value) {
  93256. if (value) {
  93257. this._cameraGazer._gazeTracker = value;
  93258. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93259. this._cameraGazer._gazeTracker.isPickable = false;
  93260. this._cameraGazer._gazeTracker.isVisible = false;
  93261. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93262. if (this.leftController) {
  93263. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93264. }
  93265. if (this.rightController) {
  93266. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93267. }
  93268. }
  93269. },
  93270. enumerable: true,
  93271. configurable: true
  93272. });
  93273. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93274. /**
  93275. * If the ray of the gaze should be displayed.
  93276. */
  93277. get: function () {
  93278. return this._displayGaze;
  93279. },
  93280. /**
  93281. * Sets if the ray of the gaze should be displayed.
  93282. */
  93283. set: function (value) {
  93284. this._displayGaze = value;
  93285. if (!value) {
  93286. this._cameraGazer._gazeTracker.isVisible = false;
  93287. if (this.leftController) {
  93288. this.leftController._gazeTracker.isVisible = false;
  93289. }
  93290. if (this.rightController) {
  93291. this.rightController._gazeTracker.isVisible = false;
  93292. }
  93293. }
  93294. },
  93295. enumerable: true,
  93296. configurable: true
  93297. });
  93298. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93299. /**
  93300. * If the ray of the LaserPointer should be displayed.
  93301. */
  93302. get: function () {
  93303. return this._displayLaserPointer;
  93304. },
  93305. /**
  93306. * Sets if the ray of the LaserPointer should be displayed.
  93307. */
  93308. set: function (value) {
  93309. this._displayLaserPointer = value;
  93310. if (!value) {
  93311. if (this.rightController) {
  93312. this.rightController._deactivatePointer();
  93313. this.rightController._gazeTracker.isVisible = false;
  93314. }
  93315. if (this.leftController) {
  93316. this.leftController._deactivatePointer();
  93317. this.leftController._gazeTracker.isVisible = false;
  93318. }
  93319. }
  93320. else {
  93321. if (this.rightController) {
  93322. this.rightController._activatePointer();
  93323. }
  93324. if (this.leftController) {
  93325. this.leftController._activatePointer();
  93326. }
  93327. }
  93328. },
  93329. enumerable: true,
  93330. configurable: true
  93331. });
  93332. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93333. /**
  93334. * The deviceOrientationCamera used as the camera when not in VR.
  93335. */
  93336. get: function () {
  93337. return this._deviceOrientationCamera;
  93338. },
  93339. enumerable: true,
  93340. configurable: true
  93341. });
  93342. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93343. /**
  93344. * Based on the current WebVR support, returns the current VR camera used.
  93345. */
  93346. get: function () {
  93347. if (this._webVRready) {
  93348. return this._webVRCamera;
  93349. }
  93350. else {
  93351. return this._scene.activeCamera;
  93352. }
  93353. },
  93354. enumerable: true,
  93355. configurable: true
  93356. });
  93357. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93358. /**
  93359. * The webVRCamera which is used when in VR.
  93360. */
  93361. get: function () {
  93362. return this._webVRCamera;
  93363. },
  93364. enumerable: true,
  93365. configurable: true
  93366. });
  93367. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93368. /**
  93369. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93370. */
  93371. get: function () {
  93372. return this._vrDeviceOrientationCamera;
  93373. },
  93374. enumerable: true,
  93375. configurable: true
  93376. });
  93377. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93378. get: function () {
  93379. var result = this._cameraGazer._teleportationRequestInitiated
  93380. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93381. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93382. return result;
  93383. },
  93384. enumerable: true,
  93385. configurable: true
  93386. });
  93387. // Raised when one of the controller has loaded successfully its associated default mesh
  93388. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93389. if (this.leftController && this.leftController.webVRController == webVRController) {
  93390. if (webVRController.mesh) {
  93391. this.leftController._setLaserPointerParent(webVRController.mesh);
  93392. }
  93393. }
  93394. if (this.rightController && this.rightController.webVRController == webVRController) {
  93395. if (webVRController.mesh) {
  93396. this.rightController._setLaserPointerParent(webVRController.mesh);
  93397. }
  93398. }
  93399. try {
  93400. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93401. }
  93402. catch (err) {
  93403. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93404. }
  93405. };
  93406. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93407. /**
  93408. * Gets a value indicating if we are currently in VR mode.
  93409. */
  93410. get: function () {
  93411. return this._webVRpresenting || this._fullscreenVRpresenting;
  93412. },
  93413. enumerable: true,
  93414. configurable: true
  93415. });
  93416. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93417. var vrDisplay = this._scene.getEngine().getVRDevice();
  93418. if (vrDisplay) {
  93419. var wasPresenting = this._webVRpresenting;
  93420. // A VR display is connected
  93421. this._webVRpresenting = vrDisplay.isPresenting;
  93422. if (wasPresenting && !this._webVRpresenting)
  93423. this.exitVR();
  93424. }
  93425. else {
  93426. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93427. }
  93428. this.updateButtonVisibility();
  93429. };
  93430. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93431. this._webVRsupported = eventArgs.vrSupported;
  93432. this._webVRready = !!eventArgs.vrDisplay;
  93433. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93434. this.updateButtonVisibility();
  93435. };
  93436. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93437. if (this._canvas && !this._useCustomVRButton) {
  93438. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93439. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93440. }
  93441. };
  93442. VRExperienceHelper.prototype.displayVRButton = function () {
  93443. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93444. document.body.appendChild(this._btnVR);
  93445. this._btnVRDisplayed = true;
  93446. }
  93447. };
  93448. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93449. if (!this._btnVR || this._useCustomVRButton) {
  93450. return;
  93451. }
  93452. this._btnVR.className = "babylonVRicon";
  93453. if (this.isInVRMode) {
  93454. this._btnVR.className += " vrdisplaypresenting";
  93455. }
  93456. else {
  93457. if (this._webVRready)
  93458. this._btnVR.className += " vrdisplayready";
  93459. if (this._webVRsupported)
  93460. this._btnVR.className += " vrdisplaysupported";
  93461. if (this._webVRrequesting)
  93462. this._btnVR.className += " vrdisplayrequesting";
  93463. }
  93464. };
  93465. /**
  93466. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93467. * Otherwise, will use the fullscreen API.
  93468. */
  93469. VRExperienceHelper.prototype.enterVR = function () {
  93470. if (this.onEnteringVRObservable) {
  93471. try {
  93472. this.onEnteringVRObservable.notifyObservers(this);
  93473. }
  93474. catch (err) {
  93475. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93476. }
  93477. }
  93478. if (this._scene.activeCamera) {
  93479. this._position = this._scene.activeCamera.position.clone();
  93480. // make sure that we return to the last active camera
  93481. this._existingCamera = this._scene.activeCamera;
  93482. }
  93483. if (this._webVRrequesting)
  93484. return;
  93485. // If WebVR is supported and a headset is connected
  93486. if (this._webVRready) {
  93487. if (!this._webVRpresenting) {
  93488. this._webVRCamera.position = this._position;
  93489. this._scene.activeCamera = this._webVRCamera;
  93490. }
  93491. }
  93492. else if (this._vrDeviceOrientationCamera) {
  93493. this._vrDeviceOrientationCamera.position = this._position;
  93494. if (this._scene.activeCamera) {
  93495. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93496. }
  93497. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93498. this._scene.getEngine().switchFullscreen(true);
  93499. this.updateButtonVisibility();
  93500. }
  93501. if (this._scene.activeCamera && this._canvas) {
  93502. this._scene.activeCamera.attachControl(this._canvas);
  93503. }
  93504. if (this._interactionsEnabled) {
  93505. this._scene.registerBeforeRender(this.beforeRender);
  93506. }
  93507. };
  93508. /**
  93509. * Attempt to exit VR, or fullscreen.
  93510. */
  93511. VRExperienceHelper.prototype.exitVR = function () {
  93512. if (this.onExitingVRObservable) {
  93513. try {
  93514. this.onExitingVRObservable.notifyObservers(this);
  93515. }
  93516. catch (err) {
  93517. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93518. }
  93519. }
  93520. if (this._webVRpresenting) {
  93521. this._scene.getEngine().disableVR();
  93522. }
  93523. if (this._scene.activeCamera) {
  93524. this._position = this._scene.activeCamera.position.clone();
  93525. }
  93526. if (this._deviceOrientationCamera) {
  93527. this._deviceOrientationCamera.position = this._position;
  93528. this._scene.activeCamera = this._deviceOrientationCamera;
  93529. if (this._canvas) {
  93530. this._scene.activeCamera.attachControl(this._canvas);
  93531. }
  93532. }
  93533. else if (this._existingCamera) {
  93534. this._existingCamera.position = this._position;
  93535. this._scene.activeCamera = this._existingCamera;
  93536. }
  93537. this.updateButtonVisibility();
  93538. if (this._interactionsEnabled) {
  93539. this._scene.unregisterBeforeRender(this.beforeRender);
  93540. }
  93541. // resize to update width and height when exiting vr exits fullscreen
  93542. this._scene.getEngine().resize();
  93543. };
  93544. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93545. /**
  93546. * The position of the vr experience helper.
  93547. */
  93548. get: function () {
  93549. return this._position;
  93550. },
  93551. /**
  93552. * Sets the position of the vr experience helper.
  93553. */
  93554. set: function (value) {
  93555. this._position = value;
  93556. if (this._scene.activeCamera) {
  93557. this._scene.activeCamera.position = value;
  93558. }
  93559. },
  93560. enumerable: true,
  93561. configurable: true
  93562. });
  93563. /**
  93564. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  93565. */
  93566. VRExperienceHelper.prototype.enableInteractions = function () {
  93567. var _this = this;
  93568. if (!this._interactionsEnabled) {
  93569. this._interactionsRequested = true;
  93570. if (this.leftController) {
  93571. this._enableInteractionOnController(this.leftController);
  93572. }
  93573. if (this.rightController) {
  93574. this._enableInteractionOnController(this.rightController);
  93575. }
  93576. this.raySelectionPredicate = function (mesh) {
  93577. return mesh.isVisible && mesh.isPickable;
  93578. };
  93579. this.meshSelectionPredicate = function (mesh) {
  93580. return true;
  93581. };
  93582. this._raySelectionPredicate = function (mesh) {
  93583. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93584. && mesh.name.indexOf("teleportationTarget") === -1
  93585. && mesh.name.indexOf("torusTeleportation") === -1)) {
  93586. return _this.raySelectionPredicate(mesh);
  93587. }
  93588. return false;
  93589. };
  93590. this._interactionsEnabled = true;
  93591. }
  93592. };
  93593. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93594. get: function () {
  93595. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93596. },
  93597. enumerable: true,
  93598. configurable: true
  93599. });
  93600. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93601. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93602. if (this._floorMeshesCollection[i].id === mesh.id) {
  93603. return true;
  93604. }
  93605. }
  93606. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93607. return true;
  93608. }
  93609. return false;
  93610. };
  93611. /**
  93612. * Adds a floor mesh to be used for teleportation.
  93613. * @param floorMesh the mesh to be used for teleportation.
  93614. */
  93615. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93616. if (!this._floorMeshesCollection) {
  93617. return;
  93618. }
  93619. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93620. return;
  93621. }
  93622. this._floorMeshesCollection.push(floorMesh);
  93623. };
  93624. /**
  93625. * Removes a floor mesh from being used for teleportation.
  93626. * @param floorMesh the mesh to be removed.
  93627. */
  93628. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93629. if (!this._floorMeshesCollection) {
  93630. return;
  93631. }
  93632. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93633. if (meshIndex !== -1) {
  93634. this._floorMeshesCollection.splice(meshIndex, 1);
  93635. }
  93636. };
  93637. /**
  93638. * Enables interactions and teleportation using the VR controllers and gaze.
  93639. * @param vrTeleportationOptions options to modify teleportation behavior.
  93640. */
  93641. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93642. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93643. if (!this._teleportationInitialized) {
  93644. this._teleportationRequested = true;
  93645. this.enableInteractions();
  93646. if (vrTeleportationOptions.floorMeshName) {
  93647. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93648. }
  93649. if (vrTeleportationOptions.floorMeshes) {
  93650. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93651. }
  93652. if (this.leftController != null) {
  93653. this._enableTeleportationOnController(this.leftController);
  93654. }
  93655. if (this.rightController != null) {
  93656. this._enableTeleportationOnController(this.rightController);
  93657. }
  93658. // Creates an image processing post process for the vignette not relying
  93659. // on the main scene configuration for image processing to reduce setup and spaces
  93660. // (gamma/linear) conflicts.
  93661. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93662. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93663. imageProcessingConfiguration.vignetteEnabled = true;
  93664. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93665. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93666. this._teleportationInitialized = true;
  93667. if (this._isDefaultTeleportationTarget) {
  93668. this._createTeleportationCircles();
  93669. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93670. }
  93671. }
  93672. };
  93673. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93674. var _this = this;
  93675. var controllerMesh = controller.webVRController.mesh;
  93676. if (controllerMesh) {
  93677. controller._interactionsEnabled = true;
  93678. controller._activatePointer();
  93679. if (this.webVROptions.laserToggle) {
  93680. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93681. // Enabling / disabling laserPointer
  93682. if (_this._displayLaserPointer && stateObject.value === 1) {
  93683. if (controller._activePointer) {
  93684. controller._deactivatePointer();
  93685. }
  93686. else {
  93687. controller._activatePointer();
  93688. }
  93689. if (_this.displayGaze) {
  93690. controller._gazeTracker.isVisible = controller._activePointer;
  93691. }
  93692. }
  93693. });
  93694. }
  93695. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93696. var gazer = controller;
  93697. if (_this._noControllerIsActive) {
  93698. gazer = _this._cameraGazer;
  93699. }
  93700. if (!gazer._pointerDownOnMeshAsked) {
  93701. if (stateObject.value > _this._padSensibilityUp) {
  93702. gazer._selectionPointerDown();
  93703. }
  93704. }
  93705. else if (stateObject.value < _this._padSensibilityDown) {
  93706. gazer._selectionPointerUp();
  93707. }
  93708. });
  93709. }
  93710. };
  93711. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93712. // Dont teleport if another gaze already requested teleportation
  93713. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93714. return;
  93715. }
  93716. if (!gazer._teleportationRequestInitiated) {
  93717. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93718. gazer._activatePointer();
  93719. gazer._teleportationRequestInitiated = true;
  93720. }
  93721. }
  93722. else {
  93723. // Listening to the proper controller values changes to confirm teleportation
  93724. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93725. if (this._teleportActive) {
  93726. this._teleportCamera(this._haloCenter);
  93727. }
  93728. gazer._teleportationRequestInitiated = false;
  93729. }
  93730. }
  93731. };
  93732. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93733. // Only rotate when user is not currently selecting a teleportation location
  93734. if (gazer._teleportationRequestInitiated) {
  93735. return;
  93736. }
  93737. if (!gazer._rotationLeftAsked) {
  93738. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93739. gazer._rotationLeftAsked = true;
  93740. if (this._rotationAllowed) {
  93741. this._rotateCamera(false);
  93742. }
  93743. }
  93744. }
  93745. else {
  93746. if (stateObject.x > -this._padSensibilityDown) {
  93747. gazer._rotationLeftAsked = false;
  93748. }
  93749. }
  93750. if (!gazer._rotationRightAsked) {
  93751. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93752. gazer._rotationRightAsked = true;
  93753. if (this._rotationAllowed) {
  93754. this._rotateCamera(true);
  93755. }
  93756. }
  93757. }
  93758. else {
  93759. if (stateObject.x < this._padSensibilityDown) {
  93760. gazer._rotationRightAsked = false;
  93761. }
  93762. }
  93763. };
  93764. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93765. // Only teleport backwards when user is not currently selecting a teleportation location
  93766. if (gazer._teleportationRequestInitiated) {
  93767. return;
  93768. }
  93769. // Teleport backwards
  93770. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93771. if (!gazer._teleportationBackRequestInitiated) {
  93772. if (!this.currentVRCamera) {
  93773. return;
  93774. }
  93775. // Get rotation and position of the current camera
  93776. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93777. var position = this.currentVRCamera.position;
  93778. // If the camera has device position, use that instead
  93779. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93780. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93781. position = this.currentVRCamera.devicePosition;
  93782. }
  93783. // Get matrix with only the y rotation of the device rotation
  93784. rotation.toEulerAnglesToRef(this._workingVector);
  93785. this._workingVector.z = 0;
  93786. this._workingVector.x = 0;
  93787. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93788. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93789. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93790. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93791. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93792. var ray = new BABYLON.Ray(position, this._workingVector);
  93793. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93794. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93795. this._teleportCamera(hit.pickedPoint);
  93796. }
  93797. gazer._teleportationBackRequestInitiated = true;
  93798. }
  93799. }
  93800. else {
  93801. gazer._teleportationBackRequestInitiated = false;
  93802. }
  93803. };
  93804. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93805. var _this = this;
  93806. var controllerMesh = controller.webVRController.mesh;
  93807. if (controllerMesh) {
  93808. if (!controller._interactionsEnabled) {
  93809. this._enableInteractionOnController(controller);
  93810. }
  93811. controller._interactionsEnabled = true;
  93812. controller._teleportationEnabled = true;
  93813. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93814. controller._dpadPressed = false;
  93815. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93816. controller._dpadPressed = stateObject.pressed;
  93817. if (!controller._dpadPressed) {
  93818. controller._rotationLeftAsked = false;
  93819. controller._rotationRightAsked = false;
  93820. controller._teleportationBackRequestInitiated = false;
  93821. }
  93822. });
  93823. }
  93824. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93825. if (_this.teleportationEnabled) {
  93826. _this._checkTeleportBackwards(stateObject, controller);
  93827. _this._checkTeleportWithRay(stateObject, controller);
  93828. }
  93829. _this._checkRotate(stateObject, controller);
  93830. });
  93831. }
  93832. };
  93833. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93834. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93835. this._teleportationTarget.isPickable = false;
  93836. var length = 512;
  93837. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93838. dynamicTexture.hasAlpha = true;
  93839. var context = dynamicTexture.getContext();
  93840. var centerX = length / 2;
  93841. var centerY = length / 2;
  93842. var radius = 200;
  93843. context.beginPath();
  93844. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93845. context.fillStyle = this._teleportationFillColor;
  93846. context.fill();
  93847. context.lineWidth = 10;
  93848. context.strokeStyle = this._teleportationBorderColor;
  93849. context.stroke();
  93850. context.closePath();
  93851. dynamicTexture.update();
  93852. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93853. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93854. this._teleportationTarget.material = teleportationCircleMaterial;
  93855. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93856. torus.isPickable = false;
  93857. torus.parent = this._teleportationTarget;
  93858. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93859. var keys = [];
  93860. keys.push({
  93861. frame: 0,
  93862. value: 0
  93863. });
  93864. keys.push({
  93865. frame: 30,
  93866. value: 0.4
  93867. });
  93868. keys.push({
  93869. frame: 60,
  93870. value: 0
  93871. });
  93872. animationInnerCircle.setKeys(keys);
  93873. var easingFunction = new BABYLON.SineEase();
  93874. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93875. animationInnerCircle.setEasingFunction(easingFunction);
  93876. torus.animations = [];
  93877. torus.animations.push(animationInnerCircle);
  93878. this._scene.beginAnimation(torus, 0, 60, true);
  93879. this._hideTeleportationTarget();
  93880. };
  93881. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93882. this._teleportActive = true;
  93883. if (this._teleportationInitialized) {
  93884. this._teleportationTarget.isVisible = true;
  93885. if (this._isDefaultTeleportationTarget) {
  93886. this._teleportationTarget.getChildren()[0].isVisible = true;
  93887. }
  93888. }
  93889. };
  93890. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93891. this._teleportActive = false;
  93892. if (this._teleportationInitialized) {
  93893. this._teleportationTarget.isVisible = false;
  93894. if (this._isDefaultTeleportationTarget) {
  93895. this._teleportationTarget.getChildren()[0].isVisible = false;
  93896. }
  93897. }
  93898. };
  93899. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93900. var _this = this;
  93901. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93902. return;
  93903. }
  93904. if (right) {
  93905. this._rotationAngle++;
  93906. }
  93907. else {
  93908. this._rotationAngle--;
  93909. }
  93910. this.currentVRCamera.animations = [];
  93911. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93912. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93913. var animationRotationKeys = [];
  93914. animationRotationKeys.push({
  93915. frame: 0,
  93916. value: this.currentVRCamera.rotationQuaternion
  93917. });
  93918. animationRotationKeys.push({
  93919. frame: 6,
  93920. value: target
  93921. });
  93922. animationRotation.setKeys(animationRotationKeys);
  93923. animationRotation.setEasingFunction(this._circleEase);
  93924. this.currentVRCamera.animations.push(animationRotation);
  93925. this._postProcessMove.animations = [];
  93926. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93927. var vignetteWeightKeys = [];
  93928. vignetteWeightKeys.push({
  93929. frame: 0,
  93930. value: 0
  93931. });
  93932. vignetteWeightKeys.push({
  93933. frame: 3,
  93934. value: 4
  93935. });
  93936. vignetteWeightKeys.push({
  93937. frame: 6,
  93938. value: 0
  93939. });
  93940. animationPP.setKeys(vignetteWeightKeys);
  93941. animationPP.setEasingFunction(this._circleEase);
  93942. this._postProcessMove.animations.push(animationPP);
  93943. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93944. var vignetteStretchKeys = [];
  93945. vignetteStretchKeys.push({
  93946. frame: 0,
  93947. value: 0
  93948. });
  93949. vignetteStretchKeys.push({
  93950. frame: 3,
  93951. value: 10
  93952. });
  93953. vignetteStretchKeys.push({
  93954. frame: 6,
  93955. value: 0
  93956. });
  93957. animationPP2.setKeys(vignetteStretchKeys);
  93958. animationPP2.setEasingFunction(this._circleEase);
  93959. this._postProcessMove.animations.push(animationPP2);
  93960. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93961. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93962. this._postProcessMove.samples = 4;
  93963. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93964. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93965. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93966. });
  93967. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93968. };
  93969. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93970. if (hit.pickedPoint) {
  93971. if (gazer._teleportationRequestInitiated) {
  93972. this._displayTeleportationTarget();
  93973. this._haloCenter.copyFrom(hit.pickedPoint);
  93974. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93975. }
  93976. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93977. if (pickNormal) {
  93978. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93979. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93980. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93981. }
  93982. this._teleportationTarget.position.y += 0.1;
  93983. }
  93984. };
  93985. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93986. var _this = this;
  93987. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93988. return;
  93989. }
  93990. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93991. // offset of the headset from the anchor.
  93992. if (this.webVRCamera.leftCamera) {
  93993. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93994. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93995. location.subtractToRef(this._workingVector, this._workingVector);
  93996. }
  93997. else {
  93998. this._workingVector.copyFrom(location);
  93999. }
  94000. // Add height to account for user's height offset
  94001. if (this.isInVRMode) {
  94002. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  94003. }
  94004. else {
  94005. this._workingVector.y += this._defaultHeight;
  94006. }
  94007. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  94008. // Create animation from the camera's position to the new location
  94009. this.currentVRCamera.animations = [];
  94010. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94011. var animationCameraTeleportationKeys = [{
  94012. frame: 0,
  94013. value: this.currentVRCamera.position
  94014. },
  94015. {
  94016. frame: 11,
  94017. value: this._workingVector
  94018. }
  94019. ];
  94020. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  94021. animationCameraTeleportation.setEasingFunction(this._circleEase);
  94022. this.currentVRCamera.animations.push(animationCameraTeleportation);
  94023. this._postProcessMove.animations = [];
  94024. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94025. var vignetteWeightKeys = [];
  94026. vignetteWeightKeys.push({
  94027. frame: 0,
  94028. value: 0
  94029. });
  94030. vignetteWeightKeys.push({
  94031. frame: 5,
  94032. value: 8
  94033. });
  94034. vignetteWeightKeys.push({
  94035. frame: 11,
  94036. value: 0
  94037. });
  94038. animationPP.setKeys(vignetteWeightKeys);
  94039. this._postProcessMove.animations.push(animationPP);
  94040. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94041. var vignetteStretchKeys = [];
  94042. vignetteStretchKeys.push({
  94043. frame: 0,
  94044. value: 0
  94045. });
  94046. vignetteStretchKeys.push({
  94047. frame: 5,
  94048. value: 10
  94049. });
  94050. vignetteStretchKeys.push({
  94051. frame: 11,
  94052. value: 0
  94053. });
  94054. animationPP2.setKeys(vignetteStretchKeys);
  94055. this._postProcessMove.animations.push(animationPP2);
  94056. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94057. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94058. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94059. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  94060. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94061. });
  94062. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  94063. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  94064. });
  94065. this._hideTeleportationTarget();
  94066. };
  94067. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  94068. if (normal) {
  94069. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  94070. if (angle < Math.PI / 2) {
  94071. normal.scaleInPlace(-1);
  94072. }
  94073. }
  94074. return normal;
  94075. };
  94076. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  94077. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94078. return;
  94079. }
  94080. var ray = gazer._getForwardRay(this._rayLength);
  94081. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94082. if (hit) {
  94083. // Populate the contrllers mesh that can be used for drag/drop
  94084. if (gazer._laserPointer) {
  94085. hit.originMesh = gazer._laserPointer.parent;
  94086. }
  94087. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  94088. }
  94089. gazer._currentHit = hit;
  94090. // Moving the gazeTracker on the mesh face targetted
  94091. if (hit && hit.pickedPoint) {
  94092. if (this._displayGaze) {
  94093. var multiplier = 1;
  94094. gazer._gazeTracker.isVisible = true;
  94095. if (gazer._isActionableMesh) {
  94096. multiplier = 3;
  94097. }
  94098. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  94099. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  94100. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  94101. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  94102. // To avoid z-fighting
  94103. var deltaFighting = 0.002;
  94104. if (pickNormal) {
  94105. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94106. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94107. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  94108. }
  94109. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  94110. if (gazer._gazeTracker.position.x < 0) {
  94111. gazer._gazeTracker.position.x += deltaFighting;
  94112. }
  94113. else {
  94114. gazer._gazeTracker.position.x -= deltaFighting;
  94115. }
  94116. if (gazer._gazeTracker.position.y < 0) {
  94117. gazer._gazeTracker.position.y += deltaFighting;
  94118. }
  94119. else {
  94120. gazer._gazeTracker.position.y -= deltaFighting;
  94121. }
  94122. if (gazer._gazeTracker.position.z < 0) {
  94123. gazer._gazeTracker.position.z += deltaFighting;
  94124. }
  94125. else {
  94126. gazer._gazeTracker.position.z -= deltaFighting;
  94127. }
  94128. }
  94129. // Changing the size of the laser pointer based on the distance from the targetted point
  94130. gazer._updatePointerDistance(hit.distance);
  94131. }
  94132. else {
  94133. gazer._updatePointerDistance();
  94134. gazer._gazeTracker.isVisible = false;
  94135. }
  94136. if (hit && hit.pickedMesh) {
  94137. // The object selected is the floor, we're in a teleportation scenario
  94138. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  94139. // Moving the teleportation area to this targetted point
  94140. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  94141. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  94142. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94143. }
  94144. gazer._currentMeshSelected = null;
  94145. if (gazer._teleportationRequestInitiated) {
  94146. this._moveTeleportationSelectorTo(hit, gazer, ray);
  94147. }
  94148. return;
  94149. }
  94150. // If not, we're in a selection scenario
  94151. //this._teleportationAllowed = false;
  94152. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  94153. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  94154. this.onNewMeshPicked.notifyObservers(hit);
  94155. gazer._currentMeshSelected = hit.pickedMesh;
  94156. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  94157. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  94158. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  94159. gazer._isActionableMesh = true;
  94160. }
  94161. else {
  94162. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94163. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94164. gazer._isActionableMesh = false;
  94165. }
  94166. try {
  94167. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  94168. }
  94169. catch (err) {
  94170. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  94171. }
  94172. }
  94173. else {
  94174. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94175. gazer._currentMeshSelected = null;
  94176. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94177. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94178. }
  94179. }
  94180. }
  94181. else {
  94182. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94183. gazer._currentMeshSelected = null;
  94184. //this._teleportationAllowed = false;
  94185. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94186. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94187. }
  94188. };
  94189. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  94190. if (mesh) {
  94191. this.onSelectedMeshUnselected.notifyObservers(mesh);
  94192. }
  94193. };
  94194. /**
  94195. * Sets the color of the laser ray from the vr controllers.
  94196. * @param color new color for the ray.
  94197. */
  94198. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94199. if (this.leftController) {
  94200. this.leftController._setLaserPointerColor(color);
  94201. }
  94202. if (this.rightController) {
  94203. this.rightController._setLaserPointerColor(color);
  94204. }
  94205. };
  94206. /**
  94207. * Sets the color of the ray from the vr headsets gaze.
  94208. * @param color new color for the ray.
  94209. */
  94210. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94211. if (!this._cameraGazer._gazeTracker.material) {
  94212. return;
  94213. }
  94214. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94215. if (this.leftController) {
  94216. this.leftController._gazeTracker.material.emissiveColor = color;
  94217. }
  94218. if (this.rightController) {
  94219. this.rightController._gazeTracker.material.emissiveColor = color;
  94220. }
  94221. };
  94222. /**
  94223. * Exits VR and disposes of the vr experience helper
  94224. */
  94225. VRExperienceHelper.prototype.dispose = function () {
  94226. if (this.isInVRMode) {
  94227. this.exitVR();
  94228. }
  94229. if (this._postProcessMove) {
  94230. this._postProcessMove.dispose();
  94231. }
  94232. if (this._webVRCamera) {
  94233. this._webVRCamera.dispose();
  94234. }
  94235. if (this._vrDeviceOrientationCamera) {
  94236. this._vrDeviceOrientationCamera.dispose();
  94237. }
  94238. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94239. document.body.removeChild(this._btnVR);
  94240. }
  94241. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94242. this._deviceOrientationCamera.dispose();
  94243. }
  94244. if (this._cameraGazer) {
  94245. this._cameraGazer.dispose();
  94246. }
  94247. if (this.leftController) {
  94248. this.leftController.dispose();
  94249. }
  94250. if (this.rightController) {
  94251. this.rightController.dispose();
  94252. }
  94253. if (this._teleportationTarget) {
  94254. this._teleportationTarget.dispose();
  94255. }
  94256. this._floorMeshesCollection = [];
  94257. document.removeEventListener("keydown", this._onKeyDown);
  94258. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94259. window.removeEventListener("resize", this._onResize);
  94260. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94261. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94262. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94263. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94264. document.onmsfullscreenchange = null;
  94265. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94266. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94267. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94268. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94269. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94270. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94271. this._scene.unregisterBeforeRender(this.beforeRender);
  94272. };
  94273. /**
  94274. * Gets the name of the VRExperienceHelper class
  94275. * @returns "VRExperienceHelper"
  94276. */
  94277. VRExperienceHelper.prototype.getClassName = function () {
  94278. return "VRExperienceHelper";
  94279. };
  94280. return VRExperienceHelper;
  94281. }());
  94282. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94283. })(BABYLON || (BABYLON = {}));
  94284. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94285. // Mainly based on these 2 articles :
  94286. // 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
  94287. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94288. var BABYLON;
  94289. (function (BABYLON) {
  94290. /**
  94291. * Defines the potential axis of a Joystick
  94292. */
  94293. var JoystickAxis;
  94294. (function (JoystickAxis) {
  94295. /** X axis */
  94296. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94297. /** Y axis */
  94298. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94299. /** Z axis */
  94300. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94301. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94302. /**
  94303. * Class used to define virtual joystick (used in touch mode)
  94304. */
  94305. var VirtualJoystick = /** @class */ (function () {
  94306. /**
  94307. * Creates a new virtual joystick
  94308. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94309. */
  94310. function VirtualJoystick(leftJoystick) {
  94311. var _this = this;
  94312. if (leftJoystick) {
  94313. this._leftJoystick = true;
  94314. }
  94315. else {
  94316. this._leftJoystick = false;
  94317. }
  94318. VirtualJoystick._globalJoystickIndex++;
  94319. // By default left & right arrow keys are moving the X
  94320. // and up & down keys are moving the Y
  94321. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94322. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94323. this.reverseLeftRight = false;
  94324. this.reverseUpDown = false;
  94325. // collections of pointers
  94326. this._touches = new BABYLON.StringDictionary();
  94327. this.deltaPosition = BABYLON.Vector3.Zero();
  94328. this._joystickSensibility = 25;
  94329. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94330. this._onResize = function (evt) {
  94331. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94332. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94333. if (VirtualJoystick.vjCanvas) {
  94334. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94335. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94336. }
  94337. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94338. };
  94339. // injecting a canvas element on top of the canvas 3D game
  94340. if (!VirtualJoystick.vjCanvas) {
  94341. window.addEventListener("resize", this._onResize, false);
  94342. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94343. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94344. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94345. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94346. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94347. VirtualJoystick.vjCanvas.style.width = "100%";
  94348. VirtualJoystick.vjCanvas.style.height = "100%";
  94349. VirtualJoystick.vjCanvas.style.position = "absolute";
  94350. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94351. VirtualJoystick.vjCanvas.style.top = "0px";
  94352. VirtualJoystick.vjCanvas.style.left = "0px";
  94353. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94354. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94355. // Support for jQuery PEP polyfill
  94356. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94357. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94358. if (!context) {
  94359. throw new Error("Unable to create canvas for virtual joystick");
  94360. }
  94361. VirtualJoystick.vjCanvasContext = context;
  94362. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94363. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94364. document.body.appendChild(VirtualJoystick.vjCanvas);
  94365. }
  94366. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94367. this.pressed = false;
  94368. // default joystick color
  94369. this._joystickColor = "cyan";
  94370. this._joystickPointerID = -1;
  94371. // current joystick position
  94372. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94373. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94374. // origin joystick position
  94375. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94376. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94377. this._onPointerDownHandlerRef = function (evt) {
  94378. _this._onPointerDown(evt);
  94379. };
  94380. this._onPointerMoveHandlerRef = function (evt) {
  94381. _this._onPointerMove(evt);
  94382. };
  94383. this._onPointerUpHandlerRef = function (evt) {
  94384. _this._onPointerUp(evt);
  94385. };
  94386. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94387. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94388. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94389. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94390. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94391. evt.preventDefault(); // Disables system menu
  94392. }, false);
  94393. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94394. }
  94395. /**
  94396. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94397. * @param newJoystickSensibility defines the new sensibility
  94398. */
  94399. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94400. this._joystickSensibility = newJoystickSensibility;
  94401. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94402. };
  94403. VirtualJoystick.prototype._onPointerDown = function (e) {
  94404. var positionOnScreenCondition;
  94405. e.preventDefault();
  94406. if (this._leftJoystick === true) {
  94407. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94408. }
  94409. else {
  94410. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94411. }
  94412. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94413. // First contact will be dedicated to the virtual joystick
  94414. this._joystickPointerID = e.pointerId;
  94415. this._joystickPointerStartPos.x = e.clientX;
  94416. this._joystickPointerStartPos.y = e.clientY;
  94417. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94418. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94419. this._deltaJoystickVector.x = 0;
  94420. this._deltaJoystickVector.y = 0;
  94421. this.pressed = true;
  94422. this._touches.add(e.pointerId.toString(), e);
  94423. }
  94424. else {
  94425. // You can only trigger the action buttons with a joystick declared
  94426. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94427. this._action();
  94428. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94429. }
  94430. }
  94431. };
  94432. VirtualJoystick.prototype._onPointerMove = function (e) {
  94433. // If the current pointer is the one associated to the joystick (first touch contact)
  94434. if (this._joystickPointerID == e.pointerId) {
  94435. this._joystickPointerPos.x = e.clientX;
  94436. this._joystickPointerPos.y = e.clientY;
  94437. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94438. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94439. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94440. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94441. switch (this._axisTargetedByLeftAndRight) {
  94442. case JoystickAxis.X:
  94443. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94444. break;
  94445. case JoystickAxis.Y:
  94446. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94447. break;
  94448. case JoystickAxis.Z:
  94449. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94450. break;
  94451. }
  94452. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94453. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94454. switch (this._axisTargetedByUpAndDown) {
  94455. case JoystickAxis.X:
  94456. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94457. break;
  94458. case JoystickAxis.Y:
  94459. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94460. break;
  94461. case JoystickAxis.Z:
  94462. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94463. break;
  94464. }
  94465. }
  94466. else {
  94467. var data = this._touches.get(e.pointerId.toString());
  94468. if (data) {
  94469. data.x = e.clientX;
  94470. data.y = e.clientY;
  94471. }
  94472. }
  94473. };
  94474. VirtualJoystick.prototype._onPointerUp = function (e) {
  94475. if (this._joystickPointerID == e.pointerId) {
  94476. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94477. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94478. this._joystickPointerID = -1;
  94479. this.pressed = false;
  94480. }
  94481. else {
  94482. var touch = this._touches.get(e.pointerId.toString());
  94483. if (touch) {
  94484. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94485. }
  94486. }
  94487. this._deltaJoystickVector.x = 0;
  94488. this._deltaJoystickVector.y = 0;
  94489. this._touches.remove(e.pointerId.toString());
  94490. };
  94491. /**
  94492. * Change the color of the virtual joystick
  94493. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94494. */
  94495. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94496. this._joystickColor = newColor;
  94497. };
  94498. /**
  94499. * Defines a callback to call when the joystick is touched
  94500. * @param action defines the callback
  94501. */
  94502. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94503. this._action = action;
  94504. };
  94505. /**
  94506. * Defines which axis you'd like to control for left & right
  94507. * @param axis defines the axis to use
  94508. */
  94509. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94510. switch (axis) {
  94511. case JoystickAxis.X:
  94512. case JoystickAxis.Y:
  94513. case JoystickAxis.Z:
  94514. this._axisTargetedByLeftAndRight = axis;
  94515. break;
  94516. default:
  94517. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94518. break;
  94519. }
  94520. };
  94521. /**
  94522. * Defines which axis you'd like to control for up & down
  94523. * @param axis defines the axis to use
  94524. */
  94525. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94526. switch (axis) {
  94527. case JoystickAxis.X:
  94528. case JoystickAxis.Y:
  94529. case JoystickAxis.Z:
  94530. this._axisTargetedByUpAndDown = axis;
  94531. break;
  94532. default:
  94533. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94534. break;
  94535. }
  94536. };
  94537. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94538. var _this = this;
  94539. if (this.pressed) {
  94540. this._touches.forEach(function (key, touch) {
  94541. if (touch.pointerId === _this._joystickPointerID) {
  94542. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94543. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94544. VirtualJoystick.vjCanvasContext.beginPath();
  94545. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94546. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94547. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94548. VirtualJoystick.vjCanvasContext.stroke();
  94549. VirtualJoystick.vjCanvasContext.closePath();
  94550. VirtualJoystick.vjCanvasContext.beginPath();
  94551. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94552. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94553. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94554. VirtualJoystick.vjCanvasContext.stroke();
  94555. VirtualJoystick.vjCanvasContext.closePath();
  94556. VirtualJoystick.vjCanvasContext.beginPath();
  94557. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94558. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94559. VirtualJoystick.vjCanvasContext.stroke();
  94560. VirtualJoystick.vjCanvasContext.closePath();
  94561. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94562. }
  94563. else {
  94564. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94565. VirtualJoystick.vjCanvasContext.beginPath();
  94566. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94567. VirtualJoystick.vjCanvasContext.beginPath();
  94568. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94569. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94570. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94571. VirtualJoystick.vjCanvasContext.stroke();
  94572. VirtualJoystick.vjCanvasContext.closePath();
  94573. touch.prevX = touch.x;
  94574. touch.prevY = touch.y;
  94575. }
  94576. ;
  94577. });
  94578. }
  94579. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94580. };
  94581. /**
  94582. * Release internal HTML canvas
  94583. */
  94584. VirtualJoystick.prototype.releaseCanvas = function () {
  94585. if (VirtualJoystick.vjCanvas) {
  94586. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94587. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94588. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94589. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94590. window.removeEventListener("resize", this._onResize);
  94591. document.body.removeChild(VirtualJoystick.vjCanvas);
  94592. VirtualJoystick.vjCanvas = null;
  94593. }
  94594. };
  94595. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94596. VirtualJoystick._globalJoystickIndex = 0;
  94597. return VirtualJoystick;
  94598. }());
  94599. BABYLON.VirtualJoystick = VirtualJoystick;
  94600. })(BABYLON || (BABYLON = {}));
  94601. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94602. var BABYLON;
  94603. (function (BABYLON) {
  94604. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  94605. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  94606. });
  94607. // We're mainly based on the logic defined into the FreeCamera code
  94608. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94609. __extends(VirtualJoysticksCamera, _super);
  94610. function VirtualJoysticksCamera(name, position, scene) {
  94611. var _this = _super.call(this, name, position, scene) || this;
  94612. _this.inputs.addVirtualJoystick();
  94613. return _this;
  94614. }
  94615. VirtualJoysticksCamera.prototype.getClassName = function () {
  94616. return "VirtualJoysticksCamera";
  94617. };
  94618. return VirtualJoysticksCamera;
  94619. }(BABYLON.FreeCamera));
  94620. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94621. })(BABYLON || (BABYLON = {}));
  94622. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94623. var BABYLON;
  94624. (function (BABYLON) {
  94625. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94626. function FreeCameraVirtualJoystickInput() {
  94627. }
  94628. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94629. return this._leftjoystick;
  94630. };
  94631. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94632. return this._rightjoystick;
  94633. };
  94634. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94635. if (this._leftjoystick) {
  94636. var camera = this.camera;
  94637. var speed = camera._computeLocalCameraSpeed() * 50;
  94638. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94639. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94640. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94641. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94642. if (!this._leftjoystick.pressed) {
  94643. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94644. }
  94645. if (!this._rightjoystick.pressed) {
  94646. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94647. }
  94648. }
  94649. };
  94650. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94651. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94652. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94653. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94654. this._leftjoystick.setJoystickSensibility(0.15);
  94655. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94656. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94657. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94658. this._rightjoystick.reverseUpDown = true;
  94659. this._rightjoystick.setJoystickSensibility(0.05);
  94660. this._rightjoystick.setJoystickColor("yellow");
  94661. };
  94662. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94663. this._leftjoystick.releaseCanvas();
  94664. this._rightjoystick.releaseCanvas();
  94665. };
  94666. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94667. return "FreeCameraVirtualJoystickInput";
  94668. };
  94669. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94670. return "virtualJoystick";
  94671. };
  94672. return FreeCameraVirtualJoystickInput;
  94673. }());
  94674. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94675. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94676. })(BABYLON || (BABYLON = {}));
  94677. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94678. var BABYLON;
  94679. (function (BABYLON) {
  94680. var SimplificationSettings = /** @class */ (function () {
  94681. function SimplificationSettings(quality, distance, optimizeMesh) {
  94682. this.quality = quality;
  94683. this.distance = distance;
  94684. this.optimizeMesh = optimizeMesh;
  94685. }
  94686. return SimplificationSettings;
  94687. }());
  94688. BABYLON.SimplificationSettings = SimplificationSettings;
  94689. var SimplificationQueue = /** @class */ (function () {
  94690. function SimplificationQueue() {
  94691. this.running = false;
  94692. this._simplificationArray = [];
  94693. }
  94694. SimplificationQueue.prototype.addTask = function (task) {
  94695. this._simplificationArray.push(task);
  94696. };
  94697. SimplificationQueue.prototype.executeNext = function () {
  94698. var task = this._simplificationArray.pop();
  94699. if (task) {
  94700. this.running = true;
  94701. this.runSimplification(task);
  94702. }
  94703. else {
  94704. this.running = false;
  94705. }
  94706. };
  94707. SimplificationQueue.prototype.runSimplification = function (task) {
  94708. var _this = this;
  94709. if (task.parallelProcessing) {
  94710. //parallel simplifier
  94711. task.settings.forEach(function (setting) {
  94712. var simplifier = _this.getSimplifier(task);
  94713. simplifier.simplify(setting, function (newMesh) {
  94714. task.mesh.addLODLevel(setting.distance, newMesh);
  94715. newMesh.isVisible = true;
  94716. //check if it is the last
  94717. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94718. //all done, run the success callback.
  94719. task.successCallback();
  94720. }
  94721. _this.executeNext();
  94722. });
  94723. });
  94724. }
  94725. else {
  94726. //single simplifier.
  94727. var simplifier = this.getSimplifier(task);
  94728. var runDecimation = function (setting, callback) {
  94729. simplifier.simplify(setting, function (newMesh) {
  94730. task.mesh.addLODLevel(setting.distance, newMesh);
  94731. newMesh.isVisible = true;
  94732. //run the next quality level
  94733. callback();
  94734. });
  94735. };
  94736. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94737. runDecimation(task.settings[loop.index], function () {
  94738. loop.executeNext();
  94739. });
  94740. }, function () {
  94741. //execution ended, run the success callback.
  94742. if (task.successCallback) {
  94743. task.successCallback();
  94744. }
  94745. _this.executeNext();
  94746. });
  94747. }
  94748. };
  94749. SimplificationQueue.prototype.getSimplifier = function (task) {
  94750. switch (task.simplificationType) {
  94751. case SimplificationType.QUADRATIC:
  94752. default:
  94753. return new QuadraticErrorSimplification(task.mesh);
  94754. }
  94755. };
  94756. return SimplificationQueue;
  94757. }());
  94758. BABYLON.SimplificationQueue = SimplificationQueue;
  94759. /**
  94760. * The implemented types of simplification
  94761. * At the moment only Quadratic Error Decimation is implemented
  94762. */
  94763. var SimplificationType;
  94764. (function (SimplificationType) {
  94765. /** Quadratic error decimation */
  94766. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94767. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94768. var DecimationTriangle = /** @class */ (function () {
  94769. function DecimationTriangle(vertices) {
  94770. this.vertices = vertices;
  94771. this.error = new Array(4);
  94772. this.deleted = false;
  94773. this.isDirty = false;
  94774. this.deletePending = false;
  94775. this.borderFactor = 0;
  94776. }
  94777. return DecimationTriangle;
  94778. }());
  94779. BABYLON.DecimationTriangle = DecimationTriangle;
  94780. var DecimationVertex = /** @class */ (function () {
  94781. function DecimationVertex(position, id) {
  94782. this.position = position;
  94783. this.id = id;
  94784. this.isBorder = true;
  94785. this.q = new QuadraticMatrix();
  94786. this.triangleCount = 0;
  94787. this.triangleStart = 0;
  94788. this.originalOffsets = [];
  94789. }
  94790. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94791. this.position.copyFrom(newPosition);
  94792. };
  94793. return DecimationVertex;
  94794. }());
  94795. BABYLON.DecimationVertex = DecimationVertex;
  94796. var QuadraticMatrix = /** @class */ (function () {
  94797. function QuadraticMatrix(data) {
  94798. this.data = new Array(10);
  94799. for (var i = 0; i < 10; ++i) {
  94800. if (data && data[i]) {
  94801. this.data[i] = data[i];
  94802. }
  94803. else {
  94804. this.data[i] = 0;
  94805. }
  94806. }
  94807. }
  94808. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94809. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94810. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94811. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94812. return det;
  94813. };
  94814. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94815. for (var i = 0; i < 10; ++i) {
  94816. this.data[i] += matrix.data[i];
  94817. }
  94818. };
  94819. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94820. for (var i = 0; i < 10; ++i) {
  94821. this.data[i] += data[i];
  94822. }
  94823. };
  94824. QuadraticMatrix.prototype.add = function (matrix) {
  94825. var m = new QuadraticMatrix();
  94826. for (var i = 0; i < 10; ++i) {
  94827. m.data[i] = this.data[i] + matrix.data[i];
  94828. }
  94829. return m;
  94830. };
  94831. QuadraticMatrix.FromData = function (a, b, c, d) {
  94832. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94833. };
  94834. //returning an array to avoid garbage collection
  94835. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94836. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94837. };
  94838. return QuadraticMatrix;
  94839. }());
  94840. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94841. var Reference = /** @class */ (function () {
  94842. function Reference(vertexId, triangleId) {
  94843. this.vertexId = vertexId;
  94844. this.triangleId = triangleId;
  94845. }
  94846. return Reference;
  94847. }());
  94848. BABYLON.Reference = Reference;
  94849. /**
  94850. * An implementation of the Quadratic Error simplification algorithm.
  94851. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94852. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94853. * @author RaananW
  94854. */
  94855. var QuadraticErrorSimplification = /** @class */ (function () {
  94856. function QuadraticErrorSimplification(_mesh) {
  94857. this._mesh = _mesh;
  94858. this.syncIterations = 5000;
  94859. this.aggressiveness = 7;
  94860. this.decimationIterations = 100;
  94861. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94862. }
  94863. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94864. var _this = this;
  94865. this.initDecimatedMesh();
  94866. //iterating through the submeshes array, one after the other.
  94867. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94868. _this.initWithMesh(loop.index, function () {
  94869. _this.runDecimation(settings, loop.index, function () {
  94870. loop.executeNext();
  94871. });
  94872. }, settings.optimizeMesh);
  94873. }, function () {
  94874. setTimeout(function () {
  94875. successCallback(_this._reconstructedMesh);
  94876. }, 0);
  94877. });
  94878. };
  94879. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94880. var _this = this;
  94881. var targetCount = ~~(this.triangles.length * settings.quality);
  94882. var deletedTriangles = 0;
  94883. var triangleCount = this.triangles.length;
  94884. var iterationFunction = function (iteration, callback) {
  94885. setTimeout(function () {
  94886. if (iteration % 5 === 0) {
  94887. _this.updateMesh(iteration === 0);
  94888. }
  94889. for (var i = 0; i < _this.triangles.length; ++i) {
  94890. _this.triangles[i].isDirty = false;
  94891. }
  94892. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94893. var trianglesIterator = function (i) {
  94894. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94895. var t = _this.triangles[tIdx];
  94896. if (!t)
  94897. return;
  94898. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94899. return;
  94900. }
  94901. for (var j = 0; j < 3; ++j) {
  94902. if (t.error[j] < threshold) {
  94903. var deleted0 = [];
  94904. var deleted1 = [];
  94905. var v0 = t.vertices[j];
  94906. var v1 = t.vertices[(j + 1) % 3];
  94907. if (v0.isBorder || v1.isBorder)
  94908. continue;
  94909. var p = BABYLON.Vector3.Zero();
  94910. var n = BABYLON.Vector3.Zero();
  94911. var uv = BABYLON.Vector2.Zero();
  94912. var color = new BABYLON.Color4(0, 0, 0, 1);
  94913. _this.calculateError(v0, v1, p, n, uv, color);
  94914. var delTr = new Array();
  94915. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94916. continue;
  94917. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94918. continue;
  94919. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94920. continue;
  94921. var uniqueArray = new Array();
  94922. delTr.forEach(function (deletedT) {
  94923. if (uniqueArray.indexOf(deletedT) === -1) {
  94924. deletedT.deletePending = true;
  94925. uniqueArray.push(deletedT);
  94926. }
  94927. });
  94928. if (uniqueArray.length % 2 !== 0) {
  94929. continue;
  94930. }
  94931. v0.q = v1.q.add(v0.q);
  94932. v0.updatePosition(p);
  94933. var tStart = _this.references.length;
  94934. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94935. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94936. var tCount = _this.references.length - tStart;
  94937. if (tCount <= v0.triangleCount) {
  94938. if (tCount) {
  94939. for (var c = 0; c < tCount; c++) {
  94940. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94941. }
  94942. }
  94943. }
  94944. else {
  94945. v0.triangleStart = tStart;
  94946. }
  94947. v0.triangleCount = tCount;
  94948. break;
  94949. }
  94950. }
  94951. };
  94952. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94953. }, 0);
  94954. };
  94955. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94956. if (triangleCount - deletedTriangles <= targetCount)
  94957. loop.breakLoop();
  94958. else {
  94959. iterationFunction(loop.index, function () {
  94960. loop.executeNext();
  94961. });
  94962. }
  94963. }, function () {
  94964. setTimeout(function () {
  94965. //reconstruct this part of the mesh
  94966. _this.reconstructMesh(submeshIndex);
  94967. successCallback();
  94968. }, 0);
  94969. });
  94970. };
  94971. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94972. var _this = this;
  94973. this.vertices = [];
  94974. this.triangles = [];
  94975. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94976. var indices = this._mesh.getIndices();
  94977. var submesh = this._mesh.subMeshes[submeshIndex];
  94978. var findInVertices = function (positionToSearch) {
  94979. if (optimizeMesh) {
  94980. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94981. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94982. return _this.vertices[ii];
  94983. }
  94984. }
  94985. }
  94986. return null;
  94987. };
  94988. var vertexReferences = [];
  94989. var vertexInit = function (i) {
  94990. if (!positionData) {
  94991. return;
  94992. }
  94993. var offset = i + submesh.verticesStart;
  94994. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94995. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94996. vertex.originalOffsets.push(offset);
  94997. if (vertex.id === _this.vertices.length) {
  94998. _this.vertices.push(vertex);
  94999. }
  95000. vertexReferences.push(vertex.id);
  95001. };
  95002. //var totalVertices = mesh.getTotalVertices();
  95003. var totalVertices = submesh.verticesCount;
  95004. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  95005. var indicesInit = function (i) {
  95006. if (!indices) {
  95007. return;
  95008. }
  95009. var offset = (submesh.indexStart / 3) + i;
  95010. var pos = (offset * 3);
  95011. var i0 = indices[pos + 0];
  95012. var i1 = indices[pos + 1];
  95013. var i2 = indices[pos + 2];
  95014. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  95015. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  95016. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  95017. var triangle = new DecimationTriangle([v0, v1, v2]);
  95018. triangle.originalOffset = pos;
  95019. _this.triangles.push(triangle);
  95020. };
  95021. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  95022. _this.init(callback);
  95023. });
  95024. });
  95025. };
  95026. QuadraticErrorSimplification.prototype.init = function (callback) {
  95027. var _this = this;
  95028. var triangleInit1 = function (i) {
  95029. var t = _this.triangles[i];
  95030. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  95031. for (var j = 0; j < 3; j++) {
  95032. 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))));
  95033. }
  95034. };
  95035. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  95036. var triangleInit2 = function (i) {
  95037. var t = _this.triangles[i];
  95038. for (var j = 0; j < 3; ++j) {
  95039. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  95040. }
  95041. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95042. };
  95043. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  95044. callback();
  95045. });
  95046. });
  95047. };
  95048. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  95049. var newTriangles = [];
  95050. var i;
  95051. for (i = 0; i < this.vertices.length; ++i) {
  95052. this.vertices[i].triangleCount = 0;
  95053. }
  95054. var t;
  95055. var j;
  95056. for (i = 0; i < this.triangles.length; ++i) {
  95057. if (!this.triangles[i].deleted) {
  95058. t = this.triangles[i];
  95059. for (j = 0; j < 3; ++j) {
  95060. t.vertices[j].triangleCount = 1;
  95061. }
  95062. newTriangles.push(t);
  95063. }
  95064. }
  95065. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  95066. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  95067. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  95068. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  95069. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  95070. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95071. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  95072. var vertexCount = 0;
  95073. for (i = 0; i < this.vertices.length; ++i) {
  95074. var vertex = this.vertices[i];
  95075. vertex.id = vertexCount;
  95076. if (vertex.triangleCount) {
  95077. vertex.originalOffsets.forEach(function (originalOffset) {
  95078. if (!normalData) {
  95079. return;
  95080. }
  95081. newPositionData.push(vertex.position.x);
  95082. newPositionData.push(vertex.position.y);
  95083. newPositionData.push(vertex.position.z);
  95084. newNormalData.push(normalData[originalOffset * 3]);
  95085. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  95086. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  95087. if (uvs && uvs.length) {
  95088. newUVsData.push(uvs[(originalOffset * 2)]);
  95089. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  95090. }
  95091. else if (colorsData && colorsData.length) {
  95092. newColorsData.push(colorsData[(originalOffset * 4)]);
  95093. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  95094. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  95095. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  95096. }
  95097. ++vertexCount;
  95098. });
  95099. }
  95100. }
  95101. var startingIndex = this._reconstructedMesh.getTotalIndices();
  95102. var startingVertex = this._reconstructedMesh.getTotalVertices();
  95103. var submeshesArray = this._reconstructedMesh.subMeshes;
  95104. this._reconstructedMesh.subMeshes = [];
  95105. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  95106. var originalIndices = this._mesh.getIndices();
  95107. for (i = 0; i < newTriangles.length; ++i) {
  95108. t = newTriangles[i]; //now get the new referencing point for each vertex
  95109. [0, 1, 2].forEach(function (idx) {
  95110. var id = originalIndices[t.originalOffset + idx];
  95111. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  95112. if (offset < 0)
  95113. offset = 0;
  95114. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  95115. });
  95116. }
  95117. //overwriting the old vertex buffers and indices.
  95118. this._reconstructedMesh.setIndices(newIndicesArray);
  95119. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  95120. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  95121. if (newUVsData.length > 0)
  95122. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  95123. if (newColorsData.length > 0)
  95124. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  95125. //create submesh
  95126. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  95127. if (submeshIndex > 0) {
  95128. this._reconstructedMesh.subMeshes = [];
  95129. submeshesArray.forEach(function (submesh) {
  95130. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  95131. });
  95132. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  95133. }
  95134. };
  95135. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  95136. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  95137. this._reconstructedMesh.material = this._mesh.material;
  95138. this._reconstructedMesh.parent = this._mesh.parent;
  95139. this._reconstructedMesh.isVisible = false;
  95140. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  95141. };
  95142. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  95143. for (var i = 0; i < vertex1.triangleCount; ++i) {
  95144. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  95145. if (t.deleted)
  95146. continue;
  95147. var s = this.references[vertex1.triangleStart + i].vertexId;
  95148. var v1 = t.vertices[(s + 1) % 3];
  95149. var v2 = t.vertices[(s + 2) % 3];
  95150. if ((v1 === vertex2 || v2 === vertex2)) {
  95151. deletedArray[i] = true;
  95152. delTr.push(t);
  95153. continue;
  95154. }
  95155. var d1 = v1.position.subtract(point);
  95156. d1 = d1.normalize();
  95157. var d2 = v2.position.subtract(point);
  95158. d2 = d2.normalize();
  95159. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  95160. return true;
  95161. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  95162. deletedArray[i] = false;
  95163. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  95164. return true;
  95165. }
  95166. return false;
  95167. };
  95168. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  95169. var newDeleted = deletedTriangles;
  95170. for (var i = 0; i < vertex.triangleCount; ++i) {
  95171. var ref = this.references[vertex.triangleStart + i];
  95172. var t = this.triangles[ref.triangleId];
  95173. if (t.deleted)
  95174. continue;
  95175. if (deletedArray[i] && t.deletePending) {
  95176. t.deleted = true;
  95177. newDeleted++;
  95178. continue;
  95179. }
  95180. t.vertices[ref.vertexId] = origVertex;
  95181. t.isDirty = true;
  95182. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  95183. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  95184. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  95185. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95186. this.references.push(ref);
  95187. }
  95188. return newDeleted;
  95189. };
  95190. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  95191. for (var i = 0; i < this.vertices.length; ++i) {
  95192. var vCount = [];
  95193. var vId = [];
  95194. var v = this.vertices[i];
  95195. var j;
  95196. for (j = 0; j < v.triangleCount; ++j) {
  95197. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95198. for (var ii = 0; ii < 3; ii++) {
  95199. var ofs = 0;
  95200. var vv = triangle.vertices[ii];
  95201. while (ofs < vCount.length) {
  95202. if (vId[ofs] === vv.id)
  95203. break;
  95204. ++ofs;
  95205. }
  95206. if (ofs === vCount.length) {
  95207. vCount.push(1);
  95208. vId.push(vv.id);
  95209. }
  95210. else {
  95211. vCount[ofs]++;
  95212. }
  95213. }
  95214. }
  95215. for (j = 0; j < vCount.length; ++j) {
  95216. if (vCount[j] === 1) {
  95217. this.vertices[vId[j]].isBorder = true;
  95218. }
  95219. else {
  95220. this.vertices[vId[j]].isBorder = false;
  95221. }
  95222. }
  95223. }
  95224. };
  95225. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95226. if (identifyBorders === void 0) { identifyBorders = false; }
  95227. var i;
  95228. if (!identifyBorders) {
  95229. var newTrianglesVector = [];
  95230. for (i = 0; i < this.triangles.length; ++i) {
  95231. if (!this.triangles[i].deleted) {
  95232. newTrianglesVector.push(this.triangles[i]);
  95233. }
  95234. }
  95235. this.triangles = newTrianglesVector;
  95236. }
  95237. for (i = 0; i < this.vertices.length; ++i) {
  95238. this.vertices[i].triangleCount = 0;
  95239. this.vertices[i].triangleStart = 0;
  95240. }
  95241. var t;
  95242. var j;
  95243. var v;
  95244. for (i = 0; i < this.triangles.length; ++i) {
  95245. t = this.triangles[i];
  95246. for (j = 0; j < 3; ++j) {
  95247. v = t.vertices[j];
  95248. v.triangleCount++;
  95249. }
  95250. }
  95251. var tStart = 0;
  95252. for (i = 0; i < this.vertices.length; ++i) {
  95253. this.vertices[i].triangleStart = tStart;
  95254. tStart += this.vertices[i].triangleCount;
  95255. this.vertices[i].triangleCount = 0;
  95256. }
  95257. var newReferences = new Array(this.triangles.length * 3);
  95258. for (i = 0; i < this.triangles.length; ++i) {
  95259. t = this.triangles[i];
  95260. for (j = 0; j < 3; ++j) {
  95261. v = t.vertices[j];
  95262. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95263. v.triangleCount++;
  95264. }
  95265. }
  95266. this.references = newReferences;
  95267. if (identifyBorders) {
  95268. this.identifyBorder();
  95269. }
  95270. };
  95271. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95272. var x = point.x;
  95273. var y = point.y;
  95274. var z = point.z;
  95275. 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
  95276. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95277. };
  95278. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95279. var q = vertex1.q.add(vertex2.q);
  95280. var border = vertex1.isBorder && vertex2.isBorder;
  95281. var error = 0;
  95282. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95283. if (qDet !== 0 && !border) {
  95284. if (!pointResult) {
  95285. pointResult = BABYLON.Vector3.Zero();
  95286. }
  95287. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95288. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95289. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95290. error = this.vertexError(q, pointResult);
  95291. }
  95292. else {
  95293. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95294. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95295. var error1 = this.vertexError(q, vertex1.position);
  95296. var error2 = this.vertexError(q, vertex2.position);
  95297. var error3 = this.vertexError(q, p3);
  95298. error = Math.min(error1, error2, error3);
  95299. if (error === error1) {
  95300. if (pointResult) {
  95301. pointResult.copyFrom(vertex1.position);
  95302. }
  95303. }
  95304. else if (error === error2) {
  95305. if (pointResult) {
  95306. pointResult.copyFrom(vertex2.position);
  95307. }
  95308. }
  95309. else {
  95310. if (pointResult) {
  95311. pointResult.copyFrom(p3);
  95312. }
  95313. }
  95314. }
  95315. return error;
  95316. };
  95317. return QuadraticErrorSimplification;
  95318. }());
  95319. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95320. })(BABYLON || (BABYLON = {}));
  95321. //# sourceMappingURL=babylon.meshSimplification.js.map
  95322. var BABYLON;
  95323. (function (BABYLON) {
  95324. var MeshLODLevel = /** @class */ (function () {
  95325. function MeshLODLevel(distance, mesh) {
  95326. this.distance = distance;
  95327. this.mesh = mesh;
  95328. }
  95329. return MeshLODLevel;
  95330. }());
  95331. BABYLON.MeshLODLevel = MeshLODLevel;
  95332. })(BABYLON || (BABYLON = {}));
  95333. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95334. var BABYLON;
  95335. (function (BABYLON) {
  95336. /**
  95337. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95338. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95339. */
  95340. var SceneOptimization = /** @class */ (function () {
  95341. /**
  95342. * Creates the SceneOptimization object
  95343. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95344. * @param desc defines the description associated with the optimization
  95345. */
  95346. function SceneOptimization(
  95347. /**
  95348. * Defines the priority of this optimization (0 by default which means first in the list)
  95349. */
  95350. priority) {
  95351. if (priority === void 0) { priority = 0; }
  95352. this.priority = priority;
  95353. }
  95354. /**
  95355. * Gets a string describing the action executed by the current optimization
  95356. * @returns description string
  95357. */
  95358. SceneOptimization.prototype.getDescription = function () {
  95359. return "";
  95360. };
  95361. /**
  95362. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95363. * @param scene defines the current scene where to apply this optimization
  95364. * @param optimizer defines the current optimizer
  95365. * @returns true if everything that can be done was applied
  95366. */
  95367. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95368. return true;
  95369. };
  95370. ;
  95371. return SceneOptimization;
  95372. }());
  95373. BABYLON.SceneOptimization = SceneOptimization;
  95374. /**
  95375. * Defines an optimization used to reduce the size of render target textures
  95376. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95377. */
  95378. var TextureOptimization = /** @class */ (function (_super) {
  95379. __extends(TextureOptimization, _super);
  95380. /**
  95381. * Creates the TextureOptimization object
  95382. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95383. * @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
  95384. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95385. */
  95386. function TextureOptimization(
  95387. /**
  95388. * Defines the priority of this optimization (0 by default which means first in the list)
  95389. */
  95390. priority,
  95391. /**
  95392. * 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
  95393. */
  95394. maximumSize,
  95395. /**
  95396. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95397. */
  95398. step) {
  95399. if (priority === void 0) { priority = 0; }
  95400. if (maximumSize === void 0) { maximumSize = 1024; }
  95401. if (step === void 0) { step = 0.5; }
  95402. var _this = _super.call(this, priority) || this;
  95403. _this.priority = priority;
  95404. _this.maximumSize = maximumSize;
  95405. _this.step = step;
  95406. return _this;
  95407. }
  95408. /**
  95409. * Gets a string describing the action executed by the current optimization
  95410. * @returns description string
  95411. */
  95412. TextureOptimization.prototype.getDescription = function () {
  95413. return "Reducing render target texture size to " + this.maximumSize;
  95414. };
  95415. /**
  95416. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95417. * @param scene defines the current scene where to apply this optimization
  95418. * @param optimizer defines the current optimizer
  95419. * @returns true if everything that can be done was applied
  95420. */
  95421. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95422. var allDone = true;
  95423. for (var index = 0; index < scene.textures.length; index++) {
  95424. var texture = scene.textures[index];
  95425. if (!texture.canRescale || texture.getContext) {
  95426. continue;
  95427. }
  95428. var currentSize = texture.getSize();
  95429. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95430. if (maxDimension > this.maximumSize) {
  95431. texture.scale(this.step);
  95432. allDone = false;
  95433. }
  95434. }
  95435. return allDone;
  95436. };
  95437. return TextureOptimization;
  95438. }(SceneOptimization));
  95439. BABYLON.TextureOptimization = TextureOptimization;
  95440. /**
  95441. * Defines an optimization used to increase or decrease the rendering resolution
  95442. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95443. */
  95444. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95445. __extends(HardwareScalingOptimization, _super);
  95446. /**
  95447. * Creates the HardwareScalingOptimization object
  95448. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95449. * @param maximumScale defines the maximum scale to use (2 by default)
  95450. * @param step defines the step to use between two passes (0.5 by default)
  95451. */
  95452. function HardwareScalingOptimization(
  95453. /**
  95454. * Defines the priority of this optimization (0 by default which means first in the list)
  95455. */
  95456. priority,
  95457. /**
  95458. * Defines the maximum scale to use (2 by default)
  95459. */
  95460. maximumScale,
  95461. /**
  95462. * Defines the step to use between two passes (0.5 by default)
  95463. */
  95464. step) {
  95465. if (priority === void 0) { priority = 0; }
  95466. if (maximumScale === void 0) { maximumScale = 2; }
  95467. if (step === void 0) { step = 0.25; }
  95468. var _this = _super.call(this, priority) || this;
  95469. _this.priority = priority;
  95470. _this.maximumScale = maximumScale;
  95471. _this.step = step;
  95472. _this._currentScale = -1;
  95473. _this._directionOffset = 1;
  95474. return _this;
  95475. }
  95476. /**
  95477. * Gets a string describing the action executed by the current optimization
  95478. * @return description string
  95479. */
  95480. HardwareScalingOptimization.prototype.getDescription = function () {
  95481. return "Setting hardware scaling level to " + this._currentScale;
  95482. };
  95483. /**
  95484. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95485. * @param scene defines the current scene where to apply this optimization
  95486. * @param optimizer defines the current optimizer
  95487. * @returns true if everything that can be done was applied
  95488. */
  95489. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95490. if (this._currentScale === -1) {
  95491. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95492. if (this._currentScale > this.maximumScale) {
  95493. this._directionOffset = -1;
  95494. }
  95495. }
  95496. this._currentScale += this._directionOffset * this.step;
  95497. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95498. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95499. };
  95500. ;
  95501. return HardwareScalingOptimization;
  95502. }(SceneOptimization));
  95503. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95504. /**
  95505. * Defines an optimization used to remove shadows
  95506. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95507. */
  95508. var ShadowsOptimization = /** @class */ (function (_super) {
  95509. __extends(ShadowsOptimization, _super);
  95510. function ShadowsOptimization() {
  95511. return _super !== null && _super.apply(this, arguments) || this;
  95512. }
  95513. /**
  95514. * Gets a string describing the action executed by the current optimization
  95515. * @return description string
  95516. */
  95517. ShadowsOptimization.prototype.getDescription = function () {
  95518. return "Turning shadows on/off";
  95519. };
  95520. /**
  95521. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95522. * @param scene defines the current scene where to apply this optimization
  95523. * @param optimizer defines the current optimizer
  95524. * @returns true if everything that can be done was applied
  95525. */
  95526. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95527. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95528. return true;
  95529. };
  95530. ;
  95531. return ShadowsOptimization;
  95532. }(SceneOptimization));
  95533. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95534. /**
  95535. * Defines an optimization used to turn post-processes off
  95536. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95537. */
  95538. var PostProcessesOptimization = /** @class */ (function (_super) {
  95539. __extends(PostProcessesOptimization, _super);
  95540. function PostProcessesOptimization() {
  95541. return _super !== null && _super.apply(this, arguments) || this;
  95542. }
  95543. /**
  95544. * Gets a string describing the action executed by the current optimization
  95545. * @return description string
  95546. */
  95547. PostProcessesOptimization.prototype.getDescription = function () {
  95548. return "Turning post-processes on/off";
  95549. };
  95550. /**
  95551. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95552. * @param scene defines the current scene where to apply this optimization
  95553. * @param optimizer defines the current optimizer
  95554. * @returns true if everything that can be done was applied
  95555. */
  95556. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95557. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95558. return true;
  95559. };
  95560. ;
  95561. return PostProcessesOptimization;
  95562. }(SceneOptimization));
  95563. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95564. /**
  95565. * Defines an optimization used to turn lens flares off
  95566. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95567. */
  95568. var LensFlaresOptimization = /** @class */ (function (_super) {
  95569. __extends(LensFlaresOptimization, _super);
  95570. function LensFlaresOptimization() {
  95571. return _super !== null && _super.apply(this, arguments) || this;
  95572. }
  95573. /**
  95574. * Gets a string describing the action executed by the current optimization
  95575. * @return description string
  95576. */
  95577. LensFlaresOptimization.prototype.getDescription = function () {
  95578. return "Turning lens flares on/off";
  95579. };
  95580. /**
  95581. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95582. * @param scene defines the current scene where to apply this optimization
  95583. * @param optimizer defines the current optimizer
  95584. * @returns true if everything that can be done was applied
  95585. */
  95586. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95587. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95588. return true;
  95589. };
  95590. ;
  95591. return LensFlaresOptimization;
  95592. }(SceneOptimization));
  95593. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95594. /**
  95595. * Defines an optimization based on user defined callback.
  95596. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95597. */
  95598. var CustomOptimization = /** @class */ (function (_super) {
  95599. __extends(CustomOptimization, _super);
  95600. function CustomOptimization() {
  95601. return _super !== null && _super.apply(this, arguments) || this;
  95602. }
  95603. /**
  95604. * Gets a string describing the action executed by the current optimization
  95605. * @returns description string
  95606. */
  95607. CustomOptimization.prototype.getDescription = function () {
  95608. if (this.onGetDescription) {
  95609. return this.onGetDescription();
  95610. }
  95611. return "Running user defined callback";
  95612. };
  95613. /**
  95614. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95615. * @param scene defines the current scene where to apply this optimization
  95616. * @param optimizer defines the current optimizer
  95617. * @returns true if everything that can be done was applied
  95618. */
  95619. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95620. if (this.onApply) {
  95621. return this.onApply(scene, optimizer);
  95622. }
  95623. return true;
  95624. };
  95625. ;
  95626. return CustomOptimization;
  95627. }(SceneOptimization));
  95628. BABYLON.CustomOptimization = CustomOptimization;
  95629. /**
  95630. * Defines an optimization used to turn particles off
  95631. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95632. */
  95633. var ParticlesOptimization = /** @class */ (function (_super) {
  95634. __extends(ParticlesOptimization, _super);
  95635. function ParticlesOptimization() {
  95636. return _super !== null && _super.apply(this, arguments) || this;
  95637. }
  95638. /**
  95639. * Gets a string describing the action executed by the current optimization
  95640. * @return description string
  95641. */
  95642. ParticlesOptimization.prototype.getDescription = function () {
  95643. return "Turning particles on/off";
  95644. };
  95645. /**
  95646. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95647. * @param scene defines the current scene where to apply this optimization
  95648. * @param optimizer defines the current optimizer
  95649. * @returns true if everything that can be done was applied
  95650. */
  95651. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95652. scene.particlesEnabled = optimizer.isInImprovementMode;
  95653. return true;
  95654. };
  95655. ;
  95656. return ParticlesOptimization;
  95657. }(SceneOptimization));
  95658. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95659. /**
  95660. * Defines an optimization used to turn render targets off
  95661. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95662. */
  95663. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95664. __extends(RenderTargetsOptimization, _super);
  95665. function RenderTargetsOptimization() {
  95666. return _super !== null && _super.apply(this, arguments) || this;
  95667. }
  95668. /**
  95669. * Gets a string describing the action executed by the current optimization
  95670. * @return description string
  95671. */
  95672. RenderTargetsOptimization.prototype.getDescription = function () {
  95673. return "Turning render targets off";
  95674. };
  95675. /**
  95676. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95677. * @param scene defines the current scene where to apply this optimization
  95678. * @param optimizer defines the current optimizer
  95679. * @returns true if everything that can be done was applied
  95680. */
  95681. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95682. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95683. return true;
  95684. };
  95685. ;
  95686. return RenderTargetsOptimization;
  95687. }(SceneOptimization));
  95688. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95689. /**
  95690. * Defines an optimization used to merge meshes with compatible materials
  95691. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95692. */
  95693. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95694. __extends(MergeMeshesOptimization, _super);
  95695. function MergeMeshesOptimization() {
  95696. var _this = _super !== null && _super.apply(this, arguments) || this;
  95697. _this._canBeMerged = function (abstractMesh) {
  95698. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95699. return false;
  95700. }
  95701. var mesh = abstractMesh;
  95702. if (mesh.isDisposed()) {
  95703. return false;
  95704. }
  95705. if (!mesh.isVisible || !mesh.isEnabled()) {
  95706. return false;
  95707. }
  95708. if (mesh.instances.length > 0) {
  95709. return false;
  95710. }
  95711. if (mesh.skeleton || mesh.hasLODLevels) {
  95712. return false;
  95713. }
  95714. return true;
  95715. };
  95716. return _this;
  95717. }
  95718. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95719. /**
  95720. * Gets or sets a boolean which defines if optimization octree has to be updated
  95721. */
  95722. get: function () {
  95723. return MergeMeshesOptimization._UpdateSelectionTree;
  95724. },
  95725. /**
  95726. * Gets or sets a boolean which defines if optimization octree has to be updated
  95727. */
  95728. set: function (value) {
  95729. MergeMeshesOptimization._UpdateSelectionTree = value;
  95730. },
  95731. enumerable: true,
  95732. configurable: true
  95733. });
  95734. /**
  95735. * Gets a string describing the action executed by the current optimization
  95736. * @return description string
  95737. */
  95738. MergeMeshesOptimization.prototype.getDescription = function () {
  95739. return "Merging similar meshes together";
  95740. };
  95741. /**
  95742. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95743. * @param scene defines the current scene where to apply this optimization
  95744. * @param optimizer defines the current optimizer
  95745. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95746. * @returns true if everything that can be done was applied
  95747. */
  95748. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95749. var globalPool = scene.meshes.slice(0);
  95750. var globalLength = globalPool.length;
  95751. for (var index = 0; index < globalLength; index++) {
  95752. var currentPool = new Array();
  95753. var current = globalPool[index];
  95754. // Checks
  95755. if (!this._canBeMerged(current)) {
  95756. continue;
  95757. }
  95758. currentPool.push(current);
  95759. // Find compatible meshes
  95760. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95761. var otherMesh = globalPool[subIndex];
  95762. if (!this._canBeMerged(otherMesh)) {
  95763. continue;
  95764. }
  95765. if (otherMesh.material !== current.material) {
  95766. continue;
  95767. }
  95768. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95769. continue;
  95770. }
  95771. currentPool.push(otherMesh);
  95772. globalLength--;
  95773. globalPool.splice(subIndex, 1);
  95774. subIndex--;
  95775. }
  95776. if (currentPool.length < 2) {
  95777. continue;
  95778. }
  95779. // Merge meshes
  95780. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95781. }
  95782. if (updateSelectionTree != undefined) {
  95783. if (updateSelectionTree) {
  95784. scene.createOrUpdateSelectionOctree();
  95785. }
  95786. }
  95787. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95788. scene.createOrUpdateSelectionOctree();
  95789. }
  95790. return true;
  95791. };
  95792. ;
  95793. MergeMeshesOptimization._UpdateSelectionTree = false;
  95794. return MergeMeshesOptimization;
  95795. }(SceneOptimization));
  95796. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95797. /**
  95798. * Defines a list of options used by SceneOptimizer
  95799. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95800. */
  95801. var SceneOptimizerOptions = /** @class */ (function () {
  95802. /**
  95803. * Creates a new list of options used by SceneOptimizer
  95804. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95805. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95806. */
  95807. function SceneOptimizerOptions(
  95808. /**
  95809. * Defines the target frame rate to reach (60 by default)
  95810. */
  95811. targetFrameRate,
  95812. /**
  95813. * Defines the interval between two checkes (2000ms by default)
  95814. */
  95815. trackerDuration) {
  95816. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95817. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95818. this.targetFrameRate = targetFrameRate;
  95819. this.trackerDuration = trackerDuration;
  95820. /**
  95821. * Gets the list of optimizations to apply
  95822. */
  95823. this.optimizations = new Array();
  95824. }
  95825. /**
  95826. * Add a new optimization
  95827. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95828. * @returns the current SceneOptimizerOptions
  95829. */
  95830. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95831. this.optimizations.push(optimization);
  95832. return this;
  95833. };
  95834. /**
  95835. * Add a new custom optimization
  95836. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95837. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95838. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95839. * @returns the current SceneOptimizerOptions
  95840. */
  95841. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95842. if (priority === void 0) { priority = 0; }
  95843. var optimization = new CustomOptimization(priority);
  95844. optimization.onApply = onApply;
  95845. optimization.onGetDescription = onGetDescription;
  95846. this.optimizations.push(optimization);
  95847. return this;
  95848. };
  95849. /**
  95850. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95851. * @param targetFrameRate defines the target frame rate (60 by default)
  95852. * @returns a SceneOptimizerOptions object
  95853. */
  95854. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95855. var result = new SceneOptimizerOptions(targetFrameRate);
  95856. var priority = 0;
  95857. result.addOptimization(new MergeMeshesOptimization(priority));
  95858. result.addOptimization(new ShadowsOptimization(priority));
  95859. result.addOptimization(new LensFlaresOptimization(priority));
  95860. // Next priority
  95861. priority++;
  95862. result.addOptimization(new PostProcessesOptimization(priority));
  95863. result.addOptimization(new ParticlesOptimization(priority));
  95864. // Next priority
  95865. priority++;
  95866. result.addOptimization(new TextureOptimization(priority, 1024));
  95867. return result;
  95868. };
  95869. /**
  95870. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95871. * @param targetFrameRate defines the target frame rate (60 by default)
  95872. * @returns a SceneOptimizerOptions object
  95873. */
  95874. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95875. var result = new SceneOptimizerOptions(targetFrameRate);
  95876. var priority = 0;
  95877. result.addOptimization(new MergeMeshesOptimization(priority));
  95878. result.addOptimization(new ShadowsOptimization(priority));
  95879. result.addOptimization(new LensFlaresOptimization(priority));
  95880. // Next priority
  95881. priority++;
  95882. result.addOptimization(new PostProcessesOptimization(priority));
  95883. result.addOptimization(new ParticlesOptimization(priority));
  95884. // Next priority
  95885. priority++;
  95886. result.addOptimization(new TextureOptimization(priority, 512));
  95887. // Next priority
  95888. priority++;
  95889. result.addOptimization(new RenderTargetsOptimization(priority));
  95890. // Next priority
  95891. priority++;
  95892. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95893. return result;
  95894. };
  95895. /**
  95896. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95897. * @param targetFrameRate defines the target frame rate (60 by default)
  95898. * @returns a SceneOptimizerOptions object
  95899. */
  95900. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95901. var result = new SceneOptimizerOptions(targetFrameRate);
  95902. var priority = 0;
  95903. result.addOptimization(new MergeMeshesOptimization(priority));
  95904. result.addOptimization(new ShadowsOptimization(priority));
  95905. result.addOptimization(new LensFlaresOptimization(priority));
  95906. // Next priority
  95907. priority++;
  95908. result.addOptimization(new PostProcessesOptimization(priority));
  95909. result.addOptimization(new ParticlesOptimization(priority));
  95910. // Next priority
  95911. priority++;
  95912. result.addOptimization(new TextureOptimization(priority, 256));
  95913. // Next priority
  95914. priority++;
  95915. result.addOptimization(new RenderTargetsOptimization(priority));
  95916. // Next priority
  95917. priority++;
  95918. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95919. return result;
  95920. };
  95921. return SceneOptimizerOptions;
  95922. }());
  95923. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95924. /**
  95925. * Class used to run optimizations in order to reach a target frame rate
  95926. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95927. */
  95928. var SceneOptimizer = /** @class */ (function () {
  95929. /**
  95930. * Creates a new SceneOptimizer
  95931. * @param scene defines the scene to work on
  95932. * @param options defines the options to use with the SceneOptimizer
  95933. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95934. * @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)
  95935. */
  95936. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95937. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95938. if (improvementMode === void 0) { improvementMode = false; }
  95939. var _this = this;
  95940. this._isRunning = false;
  95941. this._currentPriorityLevel = 0;
  95942. this._targetFrameRate = 60;
  95943. this._trackerDuration = 2000;
  95944. this._currentFrameRate = 0;
  95945. this._improvementMode = false;
  95946. /**
  95947. * Defines an observable called when the optimizer reaches the target frame rate
  95948. */
  95949. this.onSuccessObservable = new BABYLON.Observable();
  95950. /**
  95951. * Defines an observable called when the optimizer enables an optimization
  95952. */
  95953. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95954. /**
  95955. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95956. */
  95957. this.onFailureObservable = new BABYLON.Observable();
  95958. if (!options) {
  95959. this._options = new SceneOptimizerOptions();
  95960. }
  95961. else {
  95962. this._options = options;
  95963. }
  95964. if (this._options.targetFrameRate) {
  95965. this._targetFrameRate = this._options.targetFrameRate;
  95966. }
  95967. if (this._options.trackerDuration) {
  95968. this._trackerDuration = this._options.trackerDuration;
  95969. }
  95970. if (autoGeneratePriorities) {
  95971. var priority = 0;
  95972. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95973. var optim = _a[_i];
  95974. optim.priority = priority++;
  95975. }
  95976. }
  95977. this._improvementMode = improvementMode;
  95978. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95979. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95980. _this._sceneDisposeObserver = null;
  95981. _this.dispose();
  95982. });
  95983. }
  95984. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95985. /**
  95986. * Gets a boolean indicating if the optimizer is in improvement mode
  95987. */
  95988. get: function () {
  95989. return this._improvementMode;
  95990. },
  95991. enumerable: true,
  95992. configurable: true
  95993. });
  95994. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95995. /**
  95996. * Gets the current priority level (0 at start)
  95997. */
  95998. get: function () {
  95999. return this._currentPriorityLevel;
  96000. },
  96001. enumerable: true,
  96002. configurable: true
  96003. });
  96004. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  96005. /**
  96006. * Gets the current frame rate checked by the SceneOptimizer
  96007. */
  96008. get: function () {
  96009. return this._currentFrameRate;
  96010. },
  96011. enumerable: true,
  96012. configurable: true
  96013. });
  96014. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  96015. /**
  96016. * Gets or sets the current target frame rate (60 by default)
  96017. */
  96018. get: function () {
  96019. return this._targetFrameRate;
  96020. },
  96021. /**
  96022. * Gets or sets the current target frame rate (60 by default)
  96023. */
  96024. set: function (value) {
  96025. this._targetFrameRate = value;
  96026. },
  96027. enumerable: true,
  96028. configurable: true
  96029. });
  96030. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  96031. /**
  96032. * Gets or sets the current interval between two checks (every 2000ms by default)
  96033. */
  96034. get: function () {
  96035. return this._trackerDuration;
  96036. },
  96037. /**
  96038. * Gets or sets the current interval between two checks (every 2000ms by default)
  96039. */
  96040. set: function (value) {
  96041. this._trackerDuration = value;
  96042. },
  96043. enumerable: true,
  96044. configurable: true
  96045. });
  96046. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  96047. /**
  96048. * Gets the list of active optimizations
  96049. */
  96050. get: function () {
  96051. return this._options.optimizations;
  96052. },
  96053. enumerable: true,
  96054. configurable: true
  96055. });
  96056. /**
  96057. * Stops the current optimizer
  96058. */
  96059. SceneOptimizer.prototype.stop = function () {
  96060. this._isRunning = false;
  96061. };
  96062. /**
  96063. * Reset the optimizer to initial step (current priority level = 0)
  96064. */
  96065. SceneOptimizer.prototype.reset = function () {
  96066. this._currentPriorityLevel = 0;
  96067. };
  96068. /**
  96069. * Start the optimizer. By default it will try to reach a specific framerate
  96070. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  96071. */
  96072. SceneOptimizer.prototype.start = function () {
  96073. var _this = this;
  96074. if (this._isRunning) {
  96075. return;
  96076. }
  96077. this._isRunning = true;
  96078. // Let's wait for the scene to be ready before running our check
  96079. this._scene.executeWhenReady(function () {
  96080. setTimeout(function () {
  96081. _this._checkCurrentState();
  96082. }, _this._trackerDuration);
  96083. });
  96084. };
  96085. SceneOptimizer.prototype._checkCurrentState = function () {
  96086. var _this = this;
  96087. if (!this._isRunning) {
  96088. return;
  96089. }
  96090. var scene = this._scene;
  96091. var options = this._options;
  96092. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  96093. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  96094. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  96095. this._isRunning = false;
  96096. this.onSuccessObservable.notifyObservers(this);
  96097. return;
  96098. }
  96099. // Apply current level of optimizations
  96100. var allDone = true;
  96101. var noOptimizationApplied = true;
  96102. for (var index = 0; index < options.optimizations.length; index++) {
  96103. var optimization = options.optimizations[index];
  96104. if (optimization.priority === this._currentPriorityLevel) {
  96105. noOptimizationApplied = false;
  96106. allDone = allDone && optimization.apply(scene, this);
  96107. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  96108. }
  96109. }
  96110. // If no optimization was applied, this is a failure :(
  96111. if (noOptimizationApplied) {
  96112. this._isRunning = false;
  96113. this.onFailureObservable.notifyObservers(this);
  96114. return;
  96115. }
  96116. // If all optimizations were done, move to next level
  96117. if (allDone) {
  96118. this._currentPriorityLevel++;
  96119. }
  96120. // Let's the system running for a specific amount of time before checking FPS
  96121. scene.executeWhenReady(function () {
  96122. setTimeout(function () {
  96123. _this._checkCurrentState();
  96124. }, _this._trackerDuration);
  96125. });
  96126. };
  96127. /**
  96128. * Release all resources
  96129. */
  96130. SceneOptimizer.prototype.dispose = function () {
  96131. this.stop();
  96132. this.onSuccessObservable.clear();
  96133. this.onFailureObservable.clear();
  96134. this.onNewOptimizationAppliedObservable.clear();
  96135. if (this._sceneDisposeObserver) {
  96136. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96137. }
  96138. };
  96139. /**
  96140. * Helper function to create a SceneOptimizer with one single line of code
  96141. * @param scene defines the scene to work on
  96142. * @param options defines the options to use with the SceneOptimizer
  96143. * @param onSuccess defines a callback to call on success
  96144. * @param onFailure defines a callback to call on failure
  96145. * @returns the new SceneOptimizer object
  96146. */
  96147. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  96148. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  96149. if (onSuccess) {
  96150. optimizer.onSuccessObservable.add(function () {
  96151. onSuccess();
  96152. });
  96153. }
  96154. if (onFailure) {
  96155. optimizer.onFailureObservable.add(function () {
  96156. onFailure();
  96157. });
  96158. }
  96159. optimizer.start();
  96160. return optimizer;
  96161. };
  96162. return SceneOptimizer;
  96163. }());
  96164. BABYLON.SceneOptimizer = SceneOptimizer;
  96165. })(BABYLON || (BABYLON = {}));
  96166. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  96167. var BABYLON;
  96168. (function (BABYLON) {
  96169. var OutlineRenderer = /** @class */ (function () {
  96170. function OutlineRenderer(scene) {
  96171. this.zOffset = 1;
  96172. this._scene = scene;
  96173. }
  96174. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  96175. var _this = this;
  96176. if (useOverlay === void 0) { useOverlay = false; }
  96177. var scene = this._scene;
  96178. var engine = this._scene.getEngine();
  96179. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96180. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  96181. return;
  96182. }
  96183. var mesh = subMesh.getRenderingMesh();
  96184. var material = subMesh.getMaterial();
  96185. if (!material || !scene.activeCamera) {
  96186. return;
  96187. }
  96188. engine.enableEffect(this._effect);
  96189. // Logarithmic depth
  96190. if (material.useLogarithmicDepth) {
  96191. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  96192. }
  96193. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  96194. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  96195. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  96196. // Bones
  96197. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96198. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96199. }
  96200. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96201. // Alpha test
  96202. if (material && material.needAlphaTesting()) {
  96203. var alphaTexture = material.getAlphaTestTexture();
  96204. if (alphaTexture) {
  96205. this._effect.setTexture("diffuseSampler", alphaTexture);
  96206. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96207. }
  96208. }
  96209. engine.setZOffset(-this.zOffset);
  96210. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96211. engine.setZOffset(0);
  96212. };
  96213. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96214. var defines = [];
  96215. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96216. var mesh = subMesh.getMesh();
  96217. var material = subMesh.getMaterial();
  96218. if (material) {
  96219. // Alpha test
  96220. if (material.needAlphaTesting()) {
  96221. defines.push("#define ALPHATEST");
  96222. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96223. attribs.push(BABYLON.VertexBuffer.UVKind);
  96224. defines.push("#define UV1");
  96225. }
  96226. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96227. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96228. defines.push("#define UV2");
  96229. }
  96230. }
  96231. //Logarithmic depth
  96232. if (material.useLogarithmicDepth) {
  96233. defines.push("#define LOGARITHMICDEPTH");
  96234. }
  96235. }
  96236. // Bones
  96237. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96240. if (mesh.numBoneInfluencers > 4) {
  96241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96243. }
  96244. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96245. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96246. }
  96247. else {
  96248. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96249. }
  96250. // Instances
  96251. if (useInstances) {
  96252. defines.push("#define INSTANCES");
  96253. attribs.push("world0");
  96254. attribs.push("world1");
  96255. attribs.push("world2");
  96256. attribs.push("world3");
  96257. }
  96258. // Get correct effect
  96259. var join = defines.join("\n");
  96260. if (this._cachedDefines !== join) {
  96261. this._cachedDefines = join;
  96262. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96263. }
  96264. return this._effect.isReady();
  96265. };
  96266. return OutlineRenderer;
  96267. }());
  96268. BABYLON.OutlineRenderer = OutlineRenderer;
  96269. })(BABYLON || (BABYLON = {}));
  96270. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96271. var BABYLON;
  96272. (function (BABYLON) {
  96273. var FaceAdjacencies = /** @class */ (function () {
  96274. function FaceAdjacencies() {
  96275. this.edges = new Array();
  96276. this.edgesConnectedCount = 0;
  96277. }
  96278. return FaceAdjacencies;
  96279. }());
  96280. var EdgesRenderer = /** @class */ (function () {
  96281. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96282. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96283. if (epsilon === void 0) { epsilon = 0.95; }
  96284. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96285. this.edgesWidthScalerForOrthographic = 1000.0;
  96286. this.edgesWidthScalerForPerspective = 50.0;
  96287. this._linesPositions = new Array();
  96288. this._linesNormals = new Array();
  96289. this._linesIndices = new Array();
  96290. this._buffers = {};
  96291. this._checkVerticesInsteadOfIndices = false;
  96292. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96293. this.isEnabled = true;
  96294. this._source = source;
  96295. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96296. this._epsilon = epsilon;
  96297. this._prepareRessources();
  96298. this._generateEdgesLines();
  96299. }
  96300. EdgesRenderer.prototype._prepareRessources = function () {
  96301. if (this._lineShader) {
  96302. return;
  96303. }
  96304. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96305. attributes: ["position", "normal"],
  96306. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96307. });
  96308. this._lineShader.disableDepthWrite = true;
  96309. this._lineShader.backFaceCulling = false;
  96310. };
  96311. EdgesRenderer.prototype._rebuild = function () {
  96312. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96313. if (buffer) {
  96314. buffer._rebuild();
  96315. }
  96316. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96317. if (buffer) {
  96318. buffer._rebuild();
  96319. }
  96320. var scene = this._source.getScene();
  96321. var engine = scene.getEngine();
  96322. this._ib = engine.createIndexBuffer(this._linesIndices);
  96323. };
  96324. EdgesRenderer.prototype.dispose = function () {
  96325. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96326. if (buffer) {
  96327. buffer.dispose();
  96328. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96329. }
  96330. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96331. if (buffer) {
  96332. buffer.dispose();
  96333. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96334. }
  96335. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96336. this._lineShader.dispose();
  96337. };
  96338. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96339. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96340. return 0;
  96341. }
  96342. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96343. return 1;
  96344. }
  96345. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96346. return 2;
  96347. }
  96348. return -1;
  96349. };
  96350. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96351. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96352. return 0;
  96353. }
  96354. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96355. return 1;
  96356. }
  96357. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96358. return 2;
  96359. }
  96360. return -1;
  96361. };
  96362. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96363. var needToCreateLine;
  96364. if (edge === undefined) {
  96365. needToCreateLine = true;
  96366. }
  96367. else {
  96368. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96369. needToCreateLine = dotProduct < this._epsilon;
  96370. }
  96371. if (needToCreateLine) {
  96372. var offset = this._linesPositions.length / 3;
  96373. var normal = p0.subtract(p1);
  96374. normal.normalize();
  96375. // Positions
  96376. this._linesPositions.push(p0.x);
  96377. this._linesPositions.push(p0.y);
  96378. this._linesPositions.push(p0.z);
  96379. this._linesPositions.push(p0.x);
  96380. this._linesPositions.push(p0.y);
  96381. this._linesPositions.push(p0.z);
  96382. this._linesPositions.push(p1.x);
  96383. this._linesPositions.push(p1.y);
  96384. this._linesPositions.push(p1.z);
  96385. this._linesPositions.push(p1.x);
  96386. this._linesPositions.push(p1.y);
  96387. this._linesPositions.push(p1.z);
  96388. // Normals
  96389. this._linesNormals.push(p1.x);
  96390. this._linesNormals.push(p1.y);
  96391. this._linesNormals.push(p1.z);
  96392. this._linesNormals.push(-1);
  96393. this._linesNormals.push(p1.x);
  96394. this._linesNormals.push(p1.y);
  96395. this._linesNormals.push(p1.z);
  96396. this._linesNormals.push(1);
  96397. this._linesNormals.push(p0.x);
  96398. this._linesNormals.push(p0.y);
  96399. this._linesNormals.push(p0.z);
  96400. this._linesNormals.push(-1);
  96401. this._linesNormals.push(p0.x);
  96402. this._linesNormals.push(p0.y);
  96403. this._linesNormals.push(p0.z);
  96404. this._linesNormals.push(1);
  96405. // Indices
  96406. this._linesIndices.push(offset);
  96407. this._linesIndices.push(offset + 1);
  96408. this._linesIndices.push(offset + 2);
  96409. this._linesIndices.push(offset);
  96410. this._linesIndices.push(offset + 2);
  96411. this._linesIndices.push(offset + 3);
  96412. }
  96413. };
  96414. EdgesRenderer.prototype._generateEdgesLines = function () {
  96415. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96416. var indices = this._source.getIndices();
  96417. if (!indices || !positions) {
  96418. return;
  96419. }
  96420. // First let's find adjacencies
  96421. var adjacencies = new Array();
  96422. var faceNormals = new Array();
  96423. var index;
  96424. var faceAdjacencies;
  96425. // Prepare faces
  96426. for (index = 0; index < indices.length; index += 3) {
  96427. faceAdjacencies = new FaceAdjacencies();
  96428. var p0Index = indices[index];
  96429. var p1Index = indices[index + 1];
  96430. var p2Index = indices[index + 2];
  96431. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96432. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96433. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96434. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96435. faceNormal.normalize();
  96436. faceNormals.push(faceNormal);
  96437. adjacencies.push(faceAdjacencies);
  96438. }
  96439. // Scan
  96440. for (index = 0; index < adjacencies.length; index++) {
  96441. faceAdjacencies = adjacencies[index];
  96442. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96443. var otherFaceAdjacencies = adjacencies[otherIndex];
  96444. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96445. break;
  96446. }
  96447. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96448. continue;
  96449. }
  96450. var otherP0 = indices[otherIndex * 3];
  96451. var otherP1 = indices[otherIndex * 3 + 1];
  96452. var otherP2 = indices[otherIndex * 3 + 2];
  96453. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96454. var otherEdgeIndex = 0;
  96455. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96456. continue;
  96457. }
  96458. switch (edgeIndex) {
  96459. case 0:
  96460. if (this._checkVerticesInsteadOfIndices) {
  96461. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96462. }
  96463. else {
  96464. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96465. }
  96466. break;
  96467. case 1:
  96468. if (this._checkVerticesInsteadOfIndices) {
  96469. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96470. }
  96471. else {
  96472. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96473. }
  96474. break;
  96475. case 2:
  96476. if (this._checkVerticesInsteadOfIndices) {
  96477. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96478. }
  96479. else {
  96480. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96481. }
  96482. break;
  96483. }
  96484. if (otherEdgeIndex === -1) {
  96485. continue;
  96486. }
  96487. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96488. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96489. faceAdjacencies.edgesConnectedCount++;
  96490. otherFaceAdjacencies.edgesConnectedCount++;
  96491. if (faceAdjacencies.edgesConnectedCount === 3) {
  96492. break;
  96493. }
  96494. }
  96495. }
  96496. }
  96497. // Create lines
  96498. for (index = 0; index < adjacencies.length; index++) {
  96499. // 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
  96500. var current = adjacencies[index];
  96501. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96502. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96503. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96504. }
  96505. // Merge into a single mesh
  96506. var engine = this._source.getScene().getEngine();
  96507. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96508. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96509. this._ib = engine.createIndexBuffer(this._linesIndices);
  96510. this._indicesCount = this._linesIndices.length;
  96511. };
  96512. EdgesRenderer.prototype.render = function () {
  96513. var scene = this._source.getScene();
  96514. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96515. return;
  96516. }
  96517. var engine = scene.getEngine();
  96518. this._lineShader._preBind();
  96519. // VBOs
  96520. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96521. scene.resetCachedMaterial();
  96522. this._lineShader.setColor4("color", this._source.edgesColor);
  96523. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96524. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96525. }
  96526. else {
  96527. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96528. }
  96529. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96530. this._lineShader.bind(this._source.getWorldMatrix());
  96531. // Draw order
  96532. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96533. this._lineShader.unbind();
  96534. engine.setDepthWrite(true);
  96535. };
  96536. return EdgesRenderer;
  96537. }());
  96538. BABYLON.EdgesRenderer = EdgesRenderer;
  96539. })(BABYLON || (BABYLON = {}));
  96540. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96541. var BABYLON;
  96542. (function (BABYLON) {
  96543. // Adds the parser to the scene parsers.
  96544. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96545. if (parsedData.effectLayers) {
  96546. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96547. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96548. container.effectLayers.push(effectLayer);
  96549. }
  96550. }
  96551. });
  96552. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96553. var index = this.effectLayers.indexOf(toRemove);
  96554. if (index !== -1) {
  96555. this.effectLayers.splice(index, 1);
  96556. }
  96557. return index;
  96558. };
  96559. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96560. this.effectLayers.push(newEffectLayer);
  96561. };
  96562. /**
  96563. * Defines the layer scene component responsible to manage any effect layers
  96564. * in a given scene.
  96565. */
  96566. var EffectLayerSceneComponent = /** @class */ (function () {
  96567. /**
  96568. * Creates a new instance of the component for the given scene
  96569. * @param scene Defines the scene to register the component in
  96570. */
  96571. function EffectLayerSceneComponent(scene) {
  96572. /**
  96573. * The component name helpfull to identify the component in the list of scene components.
  96574. */
  96575. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96576. this._renderEffects = false;
  96577. this._needStencil = false;
  96578. this._previousStencilState = false;
  96579. this.scene = scene;
  96580. this._engine = scene.getEngine();
  96581. scene.effectLayers = new Array();
  96582. }
  96583. /**
  96584. * Registers the component in a given scene
  96585. */
  96586. EffectLayerSceneComponent.prototype.register = function () {
  96587. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96588. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96589. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96590. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96591. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96592. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96593. };
  96594. /**
  96595. * Rebuilds the elements related to this component in case of
  96596. * context lost for instance.
  96597. */
  96598. EffectLayerSceneComponent.prototype.rebuild = function () {
  96599. var layers = this.scene.effectLayers;
  96600. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  96601. var effectLayer = layers_1[_i];
  96602. effectLayer._rebuild();
  96603. }
  96604. };
  96605. /**
  96606. * Serializes the component data to the specified json object
  96607. * @param serializationObject The object to serialize to
  96608. */
  96609. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96610. // Effect layers
  96611. serializationObject.effectLayers = [];
  96612. var layers = this.scene.effectLayers;
  96613. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  96614. var effectLayer = layers_2[_i];
  96615. if (effectLayer.serialize) {
  96616. serializationObject.effectLayers.push(effectLayer.serialize());
  96617. }
  96618. }
  96619. };
  96620. /**
  96621. * Adds all the element from the container to the scene
  96622. * @param container the container holding the elements
  96623. */
  96624. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96625. var _this = this;
  96626. if (!container.effectLayers) {
  96627. return;
  96628. }
  96629. container.effectLayers.forEach(function (o) {
  96630. _this.scene.addEffectLayer(o);
  96631. });
  96632. };
  96633. /**
  96634. * Removes all the elements in the container from the scene
  96635. * @param container contains the elements to remove
  96636. */
  96637. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96638. var _this = this;
  96639. if (!container.effectLayers) {
  96640. return;
  96641. }
  96642. container.effectLayers.forEach(function (o) {
  96643. _this.scene.removeEffectLayer(o);
  96644. });
  96645. };
  96646. /**
  96647. * Disposes the component and the associated ressources.
  96648. */
  96649. EffectLayerSceneComponent.prototype.dispose = function () {
  96650. var layers = this.scene.effectLayers;
  96651. while (layers.length) {
  96652. layers[0].dispose();
  96653. }
  96654. };
  96655. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96656. var layers = this.scene.effectLayers;
  96657. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  96658. var layer = layers_3[_i];
  96659. if (!layer.hasMesh(mesh)) {
  96660. continue;
  96661. }
  96662. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  96663. var subMesh = _b[_a];
  96664. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96665. return false;
  96666. }
  96667. }
  96668. }
  96669. return true;
  96670. };
  96671. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96672. this._renderEffects = false;
  96673. this._needStencil = false;
  96674. var layers = this.scene.effectLayers;
  96675. if (layers && layers.length > 0) {
  96676. this._previousStencilState = this._engine.getStencilBuffer();
  96677. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  96678. var effectLayer = layers_4[_i];
  96679. if (effectLayer.shouldRender() &&
  96680. (!effectLayer.camera ||
  96681. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96682. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96683. this._renderEffects = true;
  96684. this._needStencil = this._needStencil || effectLayer.needStencil();
  96685. var renderTarget = effectLayer._mainTexture;
  96686. if (renderTarget._shouldRender()) {
  96687. this.scene.incrementRenderId();
  96688. renderTarget.render(false, false);
  96689. }
  96690. }
  96691. }
  96692. this.scene.incrementRenderId();
  96693. }
  96694. };
  96695. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96696. // Activate effect Layer stencil
  96697. if (this._needStencil) {
  96698. this._engine.setStencilBuffer(true);
  96699. }
  96700. };
  96701. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96702. // Restore effect Layer stencil
  96703. if (this._needStencil) {
  96704. this._engine.setStencilBuffer(this._previousStencilState);
  96705. }
  96706. };
  96707. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96708. if (this._renderEffects) {
  96709. this._engine.setDepthBuffer(false);
  96710. var layers = this.scene.effectLayers;
  96711. for (var i = 0; i < layers.length; i++) {
  96712. var effectLayer = layers[i];
  96713. if (effectLayer.renderingGroupId === renderingGroupId) {
  96714. if (effectLayer.shouldRender()) {
  96715. effectLayer.render();
  96716. }
  96717. }
  96718. }
  96719. this._engine.setDepthBuffer(true);
  96720. }
  96721. };
  96722. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96723. if (this._renderEffects) {
  96724. this._draw(-1);
  96725. }
  96726. };
  96727. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96728. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96729. this._draw(index);
  96730. }
  96731. };
  96732. return EffectLayerSceneComponent;
  96733. }());
  96734. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96735. })(BABYLON || (BABYLON = {}));
  96736. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96737. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96738. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96739. s = arguments[i];
  96740. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96741. t[p] = s[p];
  96742. }
  96743. return t;
  96744. };
  96745. var BABYLON;
  96746. (function (BABYLON) {
  96747. /**
  96748. * The effect layer Helps adding post process effect blended with the main pass.
  96749. *
  96750. * This can be for instance use to generate glow or higlight effects on the scene.
  96751. *
  96752. * The effect layer class can not be used directly and is intented to inherited from to be
  96753. * customized per effects.
  96754. */
  96755. var EffectLayer = /** @class */ (function () {
  96756. /**
  96757. * Instantiates a new effect Layer and references it in the scene.
  96758. * @param name The name of the layer
  96759. * @param scene The scene to use the layer in
  96760. */
  96761. function EffectLayer(
  96762. /** The Friendly of the effect in the scene */
  96763. name, scene) {
  96764. this._vertexBuffers = {};
  96765. this._maxSize = 0;
  96766. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96767. this._shouldRender = true;
  96768. this._postProcesses = [];
  96769. this._textures = [];
  96770. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96771. /**
  96772. * The clear color of the texture used to generate the glow map.
  96773. */
  96774. this.neutralColor = new BABYLON.Color4();
  96775. /**
  96776. * Specifies wether the highlight layer is enabled or not.
  96777. */
  96778. this.isEnabled = true;
  96779. /**
  96780. * An event triggered when the effect layer has been disposed.
  96781. */
  96782. this.onDisposeObservable = new BABYLON.Observable();
  96783. /**
  96784. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96785. */
  96786. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96787. /**
  96788. * An event triggered when the generated texture is being merged in the scene.
  96789. */
  96790. this.onBeforeComposeObservable = new BABYLON.Observable();
  96791. /**
  96792. * An event triggered when the generated texture has been merged in the scene.
  96793. */
  96794. this.onAfterComposeObservable = new BABYLON.Observable();
  96795. /**
  96796. * An event triggered when the efffect layer changes its size.
  96797. */
  96798. this.onSizeChangedObservable = new BABYLON.Observable();
  96799. this.name = name;
  96800. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96801. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96802. if (!component) {
  96803. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96804. this._scene._addComponent(component);
  96805. }
  96806. this._engine = this._scene.getEngine();
  96807. this._maxSize = this._engine.getCaps().maxTextureSize;
  96808. this._scene.effectLayers.push(this);
  96809. // Generate Buffers
  96810. this._generateIndexBuffer();
  96811. this._genrateVertexBuffer();
  96812. }
  96813. Object.defineProperty(EffectLayer.prototype, "camera", {
  96814. /**
  96815. * Gets the camera attached to the layer.
  96816. */
  96817. get: function () {
  96818. return this._effectLayerOptions.camera;
  96819. },
  96820. enumerable: true,
  96821. configurable: true
  96822. });
  96823. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96824. /**
  96825. * Gets the rendering group id the layer should render in.
  96826. */
  96827. get: function () {
  96828. return this._effectLayerOptions.renderingGroupId;
  96829. },
  96830. enumerable: true,
  96831. configurable: true
  96832. });
  96833. /**
  96834. * Initializes the effect layer with the required options.
  96835. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96836. */
  96837. EffectLayer.prototype._init = function (options) {
  96838. // Adapt options
  96839. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96840. this._setMainTextureSize();
  96841. this._createMainTexture();
  96842. this._createTextureAndPostProcesses();
  96843. this._mergeEffect = this._createMergeEffect();
  96844. };
  96845. /**
  96846. * Generates the index buffer of the full screen quad blending to the main canvas.
  96847. */
  96848. EffectLayer.prototype._generateIndexBuffer = function () {
  96849. // Indices
  96850. var indices = [];
  96851. indices.push(0);
  96852. indices.push(1);
  96853. indices.push(2);
  96854. indices.push(0);
  96855. indices.push(2);
  96856. indices.push(3);
  96857. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96858. };
  96859. /**
  96860. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96861. */
  96862. EffectLayer.prototype._genrateVertexBuffer = function () {
  96863. // VBO
  96864. var vertices = [];
  96865. vertices.push(1, 1);
  96866. vertices.push(-1, 1);
  96867. vertices.push(-1, -1);
  96868. vertices.push(1, -1);
  96869. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96870. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96871. };
  96872. /**
  96873. * Sets the main texture desired size which is the closest power of two
  96874. * of the engine canvas size.
  96875. */
  96876. EffectLayer.prototype._setMainTextureSize = function () {
  96877. if (this._effectLayerOptions.mainTextureFixedSize) {
  96878. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96879. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96880. }
  96881. else {
  96882. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96883. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96884. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96885. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96886. }
  96887. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96888. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96889. };
  96890. /**
  96891. * Creates the main texture for the effect layer.
  96892. */
  96893. EffectLayer.prototype._createMainTexture = function () {
  96894. var _this = this;
  96895. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96896. width: this._mainTextureDesiredSize.width,
  96897. height: this._mainTextureDesiredSize.height
  96898. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96899. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96900. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96901. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96902. this._mainTexture.anisotropicFilteringLevel = 1;
  96903. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96904. this._mainTexture.renderParticles = false;
  96905. this._mainTexture.renderList = null;
  96906. this._mainTexture.ignoreCameraViewport = true;
  96907. // Custom render function
  96908. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96909. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96910. var index;
  96911. var engine = _this._scene.getEngine();
  96912. if (depthOnlySubMeshes.length) {
  96913. engine.setColorWrite(false);
  96914. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96915. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96916. }
  96917. engine.setColorWrite(true);
  96918. }
  96919. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96920. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96921. }
  96922. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96923. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96924. }
  96925. for (index = 0; index < transparentSubMeshes.length; index++) {
  96926. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96927. }
  96928. };
  96929. this._mainTexture.onClearObservable.add(function (engine) {
  96930. engine.clear(_this.neutralColor, true, true, true);
  96931. });
  96932. };
  96933. /**
  96934. * Checks for the readiness of the element composing the layer.
  96935. * @param subMesh the mesh to check for
  96936. * @param useInstances specify wether or not to use instances to render the mesh
  96937. * @param emissiveTexture the associated emissive texture used to generate the glow
  96938. * @return true if ready otherwise, false
  96939. */
  96940. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96941. var material = subMesh.getMaterial();
  96942. if (!material) {
  96943. return false;
  96944. }
  96945. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96946. return false;
  96947. }
  96948. var defines = [];
  96949. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96950. var mesh = subMesh.getMesh();
  96951. var uv1 = false;
  96952. var uv2 = false;
  96953. // Alpha test
  96954. if (material && material.needAlphaTesting()) {
  96955. var alphaTexture = material.getAlphaTestTexture();
  96956. if (alphaTexture) {
  96957. defines.push("#define ALPHATEST");
  96958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96959. alphaTexture.coordinatesIndex === 1) {
  96960. defines.push("#define DIFFUSEUV2");
  96961. uv2 = true;
  96962. }
  96963. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96964. defines.push("#define DIFFUSEUV1");
  96965. uv1 = true;
  96966. }
  96967. }
  96968. }
  96969. // Emissive
  96970. if (emissiveTexture) {
  96971. defines.push("#define EMISSIVE");
  96972. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96973. emissiveTexture.coordinatesIndex === 1) {
  96974. defines.push("#define EMISSIVEUV2");
  96975. uv2 = true;
  96976. }
  96977. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96978. defines.push("#define EMISSIVEUV1");
  96979. uv1 = true;
  96980. }
  96981. }
  96982. if (uv1) {
  96983. attribs.push(BABYLON.VertexBuffer.UVKind);
  96984. defines.push("#define UV1");
  96985. }
  96986. if (uv2) {
  96987. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96988. defines.push("#define UV2");
  96989. }
  96990. // Bones
  96991. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96994. if (mesh.numBoneInfluencers > 4) {
  96995. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96996. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96997. }
  96998. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96999. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  97000. }
  97001. else {
  97002. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97003. }
  97004. // Morph targets
  97005. var manager = mesh.morphTargetManager;
  97006. var morphInfluencers = 0;
  97007. if (manager) {
  97008. if (manager.numInfluencers > 0) {
  97009. defines.push("#define MORPHTARGETS");
  97010. morphInfluencers = manager.numInfluencers;
  97011. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  97012. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  97013. }
  97014. }
  97015. // Instances
  97016. if (useInstances) {
  97017. defines.push("#define INSTANCES");
  97018. attribs.push("world0");
  97019. attribs.push("world1");
  97020. attribs.push("world2");
  97021. attribs.push("world3");
  97022. }
  97023. // Get correct effect
  97024. var join = defines.join("\n");
  97025. if (this._cachedDefines !== join) {
  97026. this._cachedDefines = join;
  97027. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  97028. }
  97029. return this._effectLayerMapGenerationEffect.isReady();
  97030. };
  97031. /**
  97032. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  97033. */
  97034. EffectLayer.prototype.render = function () {
  97035. var currentEffect = this._mergeEffect;
  97036. // Check
  97037. if (!currentEffect.isReady())
  97038. return;
  97039. for (var i = 0; i < this._postProcesses.length; i++) {
  97040. if (!this._postProcesses[i].isReady()) {
  97041. return;
  97042. }
  97043. }
  97044. var engine = this._scene.getEngine();
  97045. this.onBeforeComposeObservable.notifyObservers(this);
  97046. // Render
  97047. engine.enableEffect(currentEffect);
  97048. engine.setState(false);
  97049. // VBOs
  97050. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97051. // Cache
  97052. var previousAlphaMode = engine.getAlphaMode();
  97053. // Go Blend.
  97054. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  97055. // Blends the map on the main canvas.
  97056. this._internalRender(currentEffect);
  97057. // Restore Alpha
  97058. engine.setAlphaMode(previousAlphaMode);
  97059. this.onAfterComposeObservable.notifyObservers(this);
  97060. // Handle size changes.
  97061. var size = this._mainTexture.getSize();
  97062. this._setMainTextureSize();
  97063. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  97064. // Recreate RTT and post processes on size change.
  97065. this.onSizeChangedObservable.notifyObservers(this);
  97066. this._disposeTextureAndPostProcesses();
  97067. this._createMainTexture();
  97068. this._createTextureAndPostProcesses();
  97069. }
  97070. };
  97071. /**
  97072. * Determine if a given mesh will be used in the current effect.
  97073. * @param mesh mesh to test
  97074. * @returns true if the mesh will be used
  97075. */
  97076. EffectLayer.prototype.hasMesh = function (mesh) {
  97077. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  97078. return true;
  97079. }
  97080. return false;
  97081. };
  97082. /**
  97083. * Returns true if the layer contains information to display, otherwise false.
  97084. * @returns true if the glow layer should be rendered
  97085. */
  97086. EffectLayer.prototype.shouldRender = function () {
  97087. return this.isEnabled && this._shouldRender;
  97088. };
  97089. /**
  97090. * Returns true if the mesh should render, otherwise false.
  97091. * @param mesh The mesh to render
  97092. * @returns true if it should render otherwise false
  97093. */
  97094. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  97095. return true;
  97096. };
  97097. /**
  97098. * Returns true if the mesh should render, otherwise false.
  97099. * @param mesh The mesh to render
  97100. * @returns true if it should render otherwise false
  97101. */
  97102. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  97103. return true;
  97104. };
  97105. /**
  97106. * Renders the submesh passed in parameter to the generation map.
  97107. */
  97108. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  97109. var _this = this;
  97110. if (!this.shouldRender()) {
  97111. return;
  97112. }
  97113. var material = subMesh.getMaterial();
  97114. var mesh = subMesh.getRenderingMesh();
  97115. var scene = this._scene;
  97116. var engine = scene.getEngine();
  97117. if (!material) {
  97118. return;
  97119. }
  97120. // Do not block in blend mode.
  97121. if (material.needAlphaBlendingForMesh(mesh)) {
  97122. return;
  97123. }
  97124. // Culling
  97125. engine.setState(material.backFaceCulling);
  97126. // Managing instances
  97127. var batch = mesh._getInstancesRenderList(subMesh._id);
  97128. if (batch.mustReturn) {
  97129. return;
  97130. }
  97131. // Early Exit per mesh
  97132. if (!this._shouldRenderMesh(mesh)) {
  97133. return;
  97134. }
  97135. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97136. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  97137. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  97138. engine.enableEffect(this._effectLayerMapGenerationEffect);
  97139. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  97140. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  97141. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  97142. // Alpha test
  97143. if (material && material.needAlphaTesting()) {
  97144. var alphaTexture = material.getAlphaTestTexture();
  97145. if (alphaTexture) {
  97146. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  97147. var textureMatrix = alphaTexture.getTextureMatrix();
  97148. if (textureMatrix) {
  97149. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  97150. }
  97151. }
  97152. }
  97153. // Glow emissive only
  97154. if (this._emissiveTextureAndColor.texture) {
  97155. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  97156. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  97157. }
  97158. // Bones
  97159. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97160. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97161. }
  97162. // Morph targets
  97163. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  97164. // Draw
  97165. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  97166. }
  97167. else {
  97168. // Need to reset refresh rate of the main map
  97169. this._mainTexture.resetRefreshCounter();
  97170. }
  97171. };
  97172. /**
  97173. * Rebuild the required buffers.
  97174. * @hidden Internal use only.
  97175. */
  97176. EffectLayer.prototype._rebuild = function () {
  97177. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97178. if (vb) {
  97179. vb._rebuild();
  97180. }
  97181. this._generateIndexBuffer();
  97182. };
  97183. /**
  97184. * Dispose only the render target textures and post process.
  97185. */
  97186. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  97187. this._mainTexture.dispose();
  97188. for (var i = 0; i < this._postProcesses.length; i++) {
  97189. if (this._postProcesses[i]) {
  97190. this._postProcesses[i].dispose();
  97191. }
  97192. }
  97193. this._postProcesses = [];
  97194. for (var i = 0; i < this._textures.length; i++) {
  97195. if (this._textures[i]) {
  97196. this._textures[i].dispose();
  97197. }
  97198. }
  97199. this._textures = [];
  97200. };
  97201. /**
  97202. * Dispose the highlight layer and free resources.
  97203. */
  97204. EffectLayer.prototype.dispose = function () {
  97205. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97206. if (vertexBuffer) {
  97207. vertexBuffer.dispose();
  97208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97209. }
  97210. if (this._indexBuffer) {
  97211. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97212. this._indexBuffer = null;
  97213. }
  97214. // Clean textures and post processes
  97215. this._disposeTextureAndPostProcesses();
  97216. // Remove from scene
  97217. var index = this._scene.effectLayers.indexOf(this, 0);
  97218. if (index > -1) {
  97219. this._scene.effectLayers.splice(index, 1);
  97220. }
  97221. // Callback
  97222. this.onDisposeObservable.notifyObservers(this);
  97223. this.onDisposeObservable.clear();
  97224. this.onBeforeRenderMainTextureObservable.clear();
  97225. this.onBeforeComposeObservable.clear();
  97226. this.onAfterComposeObservable.clear();
  97227. this.onSizeChangedObservable.clear();
  97228. };
  97229. /**
  97230. * Gets the class name of the effect layer
  97231. * @returns the string with the class name of the effect layer
  97232. */
  97233. EffectLayer.prototype.getClassName = function () {
  97234. return "EffectLayer";
  97235. };
  97236. /**
  97237. * Creates an effect layer from parsed effect layer data
  97238. * @param parsedEffectLayer defines effect layer data
  97239. * @param scene defines the current scene
  97240. * @param rootUrl defines the root URL containing the effect layer information
  97241. * @returns a parsed effect Layer
  97242. */
  97243. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97244. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97245. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97246. };
  97247. __decorate([
  97248. BABYLON.serialize()
  97249. ], EffectLayer.prototype, "name", void 0);
  97250. __decorate([
  97251. BABYLON.serializeAsColor4()
  97252. ], EffectLayer.prototype, "neutralColor", void 0);
  97253. __decorate([
  97254. BABYLON.serialize()
  97255. ], EffectLayer.prototype, "isEnabled", void 0);
  97256. __decorate([
  97257. BABYLON.serializeAsCameraReference()
  97258. ], EffectLayer.prototype, "camera", null);
  97259. __decorate([
  97260. BABYLON.serialize()
  97261. ], EffectLayer.prototype, "renderingGroupId", null);
  97262. return EffectLayer;
  97263. }());
  97264. BABYLON.EffectLayer = EffectLayer;
  97265. })(BABYLON || (BABYLON = {}));
  97266. //# sourceMappingURL=babylon.effectLayer.js.map
  97267. var BABYLON;
  97268. (function (BABYLON) {
  97269. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97270. for (var index = 0; index < this.effectLayers.length; index++) {
  97271. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97272. return this.effectLayers[index];
  97273. }
  97274. }
  97275. return null;
  97276. };
  97277. /**
  97278. * Special Glow Blur post process only blurring the alpha channel
  97279. * It enforces keeping the most luminous color in the color channel.
  97280. */
  97281. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97282. __extends(GlowBlurPostProcess, _super);
  97283. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97285. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97286. _this.direction = direction;
  97287. _this.kernel = kernel;
  97288. _this.onApplyObservable.add(function (effect) {
  97289. effect.setFloat2("screenSize", _this.width, _this.height);
  97290. effect.setVector2("direction", _this.direction);
  97291. effect.setFloat("blurWidth", _this.kernel);
  97292. });
  97293. return _this;
  97294. }
  97295. return GlowBlurPostProcess;
  97296. }(BABYLON.PostProcess));
  97297. /**
  97298. * The highlight layer Helps adding a glow effect around a mesh.
  97299. *
  97300. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97301. * glowy meshes to your scene.
  97302. *
  97303. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97304. */
  97305. var HighlightLayer = /** @class */ (function (_super) {
  97306. __extends(HighlightLayer, _super);
  97307. /**
  97308. * Instantiates a new highlight Layer and references it to the scene..
  97309. * @param name The name of the layer
  97310. * @param scene The scene to use the layer in
  97311. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97312. */
  97313. function HighlightLayer(name, scene, options) {
  97314. var _this = _super.call(this, name, scene) || this;
  97315. _this.name = name;
  97316. /**
  97317. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97318. */
  97319. _this.innerGlow = true;
  97320. /**
  97321. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97322. */
  97323. _this.outerGlow = true;
  97324. /**
  97325. * An event triggered when the highlight layer is being blurred.
  97326. */
  97327. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97328. /**
  97329. * An event triggered when the highlight layer has been blurred.
  97330. */
  97331. _this.onAfterBlurObservable = new BABYLON.Observable();
  97332. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97333. _this._meshes = {};
  97334. _this._excludedMeshes = {};
  97335. _this.neutralColor = HighlightLayer.NeutralColor;
  97336. // Warn on stencil
  97337. if (!_this._engine.isStencilEnable) {
  97338. 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 }");
  97339. }
  97340. // Adapt options
  97341. _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);
  97342. // Initialize the layer
  97343. _this._init({
  97344. alphaBlendingMode: _this._options.alphaBlendingMode,
  97345. camera: _this._options.camera,
  97346. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97347. mainTextureRatio: _this._options.mainTextureRatio,
  97348. renderingGroupId: _this._options.renderingGroupId
  97349. });
  97350. // Do not render as long as no meshes have been added
  97351. _this._shouldRender = false;
  97352. return _this;
  97353. }
  97354. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97355. /**
  97356. * Gets the horizontal size of the blur.
  97357. */
  97358. get: function () {
  97359. return this._horizontalBlurPostprocess.kernel;
  97360. },
  97361. /**
  97362. * Specifies the horizontal size of the blur.
  97363. */
  97364. set: function (value) {
  97365. this._horizontalBlurPostprocess.kernel = value;
  97366. },
  97367. enumerable: true,
  97368. configurable: true
  97369. });
  97370. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97371. /**
  97372. * Gets the vertical size of the blur.
  97373. */
  97374. get: function () {
  97375. return this._verticalBlurPostprocess.kernel;
  97376. },
  97377. /**
  97378. * Specifies the vertical size of the blur.
  97379. */
  97380. set: function (value) {
  97381. this._verticalBlurPostprocess.kernel = value;
  97382. },
  97383. enumerable: true,
  97384. configurable: true
  97385. });
  97386. /**
  97387. * Get the effect name of the layer.
  97388. * @return The effect name
  97389. */
  97390. HighlightLayer.prototype.getEffectName = function () {
  97391. return HighlightLayer.EffectName;
  97392. };
  97393. /**
  97394. * Create the merge effect. This is the shader use to blit the information back
  97395. * to the main canvas at the end of the scene rendering.
  97396. */
  97397. HighlightLayer.prototype._createMergeEffect = function () {
  97398. // Effect
  97399. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97400. };
  97401. /**
  97402. * Creates the render target textures and post processes used in the highlight layer.
  97403. */
  97404. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97405. var _this = this;
  97406. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97407. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97408. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97409. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97410. var textureType = 0;
  97411. if (this._engine.getCaps().textureHalfFloatRender) {
  97412. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97413. }
  97414. else {
  97415. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97416. }
  97417. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97418. width: blurTextureWidth,
  97419. height: blurTextureHeight
  97420. }, this._scene, false, true, textureType);
  97421. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97422. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97423. this._blurTexture.anisotropicFilteringLevel = 16;
  97424. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97425. this._blurTexture.renderParticles = false;
  97426. this._blurTexture.ignoreCameraViewport = true;
  97427. this._textures = [this._blurTexture];
  97428. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97429. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97430. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97431. effect.setTexture("textureSampler", _this._mainTexture);
  97432. });
  97433. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97434. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97435. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97436. });
  97437. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97438. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97439. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97440. });
  97441. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97442. }
  97443. else {
  97444. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97445. width: blurTextureWidth,
  97446. height: blurTextureHeight
  97447. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97448. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97449. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97450. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97451. effect.setTexture("textureSampler", _this._mainTexture);
  97452. });
  97453. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97454. width: blurTextureWidth,
  97455. height: blurTextureHeight
  97456. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97457. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97458. }
  97459. this._mainTexture.onAfterUnbindObservable.add(function () {
  97460. _this.onBeforeBlurObservable.notifyObservers(_this);
  97461. var internalTexture = _this._blurTexture.getInternalTexture();
  97462. if (internalTexture) {
  97463. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97464. }
  97465. _this.onAfterBlurObservable.notifyObservers(_this);
  97466. });
  97467. // Prevent autoClear.
  97468. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97469. };
  97470. /**
  97471. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97472. */
  97473. HighlightLayer.prototype.needStencil = function () {
  97474. return true;
  97475. };
  97476. /**
  97477. * Checks for the readiness of the element composing the layer.
  97478. * @param subMesh the mesh to check for
  97479. * @param useInstances specify wether or not to use instances to render the mesh
  97480. * @param emissiveTexture the associated emissive texture used to generate the glow
  97481. * @return true if ready otherwise, false
  97482. */
  97483. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97484. var material = subMesh.getMaterial();
  97485. var mesh = subMesh.getRenderingMesh();
  97486. if (!material || !mesh || !this._meshes) {
  97487. return false;
  97488. }
  97489. var emissiveTexture = null;
  97490. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97491. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97492. emissiveTexture = material.emissiveTexture;
  97493. }
  97494. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97495. };
  97496. /**
  97497. * Implementation specific of rendering the generating effect on the main canvas.
  97498. * @param effect The effect used to render through
  97499. */
  97500. HighlightLayer.prototype._internalRender = function (effect) {
  97501. // Texture
  97502. effect.setTexture("textureSampler", this._blurTexture);
  97503. // Cache
  97504. var engine = this._engine;
  97505. var previousStencilBuffer = engine.getStencilBuffer();
  97506. var previousStencilFunction = engine.getStencilFunction();
  97507. var previousStencilMask = engine.getStencilMask();
  97508. var previousStencilOperationPass = engine.getStencilOperationPass();
  97509. var previousStencilOperationFail = engine.getStencilOperationFail();
  97510. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97511. var previousStencilReference = engine.getStencilFunctionReference();
  97512. // Stencil operations
  97513. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97514. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97515. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97516. // Draw order
  97517. engine.setStencilMask(0x00);
  97518. engine.setStencilBuffer(true);
  97519. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97520. // 2 passes inner outer
  97521. if (this.outerGlow) {
  97522. effect.setFloat("offset", 0);
  97523. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97524. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97525. }
  97526. if (this.innerGlow) {
  97527. effect.setFloat("offset", 1);
  97528. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97529. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97530. }
  97531. // Restore Cache
  97532. engine.setStencilFunction(previousStencilFunction);
  97533. engine.setStencilMask(previousStencilMask);
  97534. engine.setStencilBuffer(previousStencilBuffer);
  97535. engine.setStencilOperationPass(previousStencilOperationPass);
  97536. engine.setStencilOperationFail(previousStencilOperationFail);
  97537. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97538. engine.setStencilFunctionReference(previousStencilReference);
  97539. };
  97540. /**
  97541. * Returns true if the layer contains information to display, otherwise false.
  97542. */
  97543. HighlightLayer.prototype.shouldRender = function () {
  97544. if (_super.prototype.shouldRender.call(this)) {
  97545. return this._meshes ? true : false;
  97546. }
  97547. return false;
  97548. };
  97549. /**
  97550. * Returns true if the mesh should render, otherwise false.
  97551. * @param mesh The mesh to render
  97552. * @returns true if it should render otherwise false
  97553. */
  97554. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97555. // Excluded Mesh
  97556. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97557. return false;
  97558. }
  97559. ;
  97560. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97561. return false;
  97562. }
  97563. return true;
  97564. };
  97565. /**
  97566. * Sets the required values for both the emissive texture and and the main color.
  97567. */
  97568. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97569. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97570. if (highlightLayerMesh) {
  97571. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97572. }
  97573. else {
  97574. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97575. }
  97576. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97577. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97578. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97579. }
  97580. else {
  97581. this._emissiveTextureAndColor.texture = null;
  97582. }
  97583. };
  97584. /**
  97585. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97586. * @param mesh The mesh to exclude from the highlight layer
  97587. */
  97588. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97589. if (!this._excludedMeshes) {
  97590. return;
  97591. }
  97592. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97593. if (!meshExcluded) {
  97594. this._excludedMeshes[mesh.uniqueId] = {
  97595. mesh: mesh,
  97596. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97597. mesh.getEngine().setStencilBuffer(false);
  97598. }),
  97599. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97600. mesh.getEngine().setStencilBuffer(true);
  97601. }),
  97602. };
  97603. }
  97604. };
  97605. /**
  97606. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97607. * @param mesh The mesh to highlight
  97608. */
  97609. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97610. if (!this._excludedMeshes) {
  97611. return;
  97612. }
  97613. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97614. if (meshExcluded) {
  97615. if (meshExcluded.beforeRender) {
  97616. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97617. }
  97618. if (meshExcluded.afterRender) {
  97619. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97620. }
  97621. }
  97622. this._excludedMeshes[mesh.uniqueId] = null;
  97623. };
  97624. /**
  97625. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97626. * @param mesh mesh to test
  97627. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97628. */
  97629. HighlightLayer.prototype.hasMesh = function (mesh) {
  97630. if (!this._meshes) {
  97631. return false;
  97632. }
  97633. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97634. return false;
  97635. }
  97636. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97637. };
  97638. /**
  97639. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97640. * @param mesh The mesh to highlight
  97641. * @param color The color of the highlight
  97642. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97643. */
  97644. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97645. var _this = this;
  97646. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97647. if (!this._meshes) {
  97648. return;
  97649. }
  97650. var meshHighlight = this._meshes[mesh.uniqueId];
  97651. if (meshHighlight) {
  97652. meshHighlight.color = color;
  97653. }
  97654. else {
  97655. this._meshes[mesh.uniqueId] = {
  97656. mesh: mesh,
  97657. color: color,
  97658. // Lambda required for capture due to Observable this context
  97659. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97660. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97661. _this._defaultStencilReference(mesh);
  97662. }
  97663. else {
  97664. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97665. }
  97666. }),
  97667. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97668. glowEmissiveOnly: glowEmissiveOnly
  97669. };
  97670. mesh.onDisposeObservable.add(function () {
  97671. _this._disposeMesh(mesh);
  97672. });
  97673. }
  97674. this._shouldRender = true;
  97675. };
  97676. /**
  97677. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97678. * @param mesh The mesh to highlight
  97679. */
  97680. HighlightLayer.prototype.removeMesh = function (mesh) {
  97681. if (!this._meshes) {
  97682. return;
  97683. }
  97684. var meshHighlight = this._meshes[mesh.uniqueId];
  97685. if (meshHighlight) {
  97686. if (meshHighlight.observerHighlight) {
  97687. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97688. }
  97689. if (meshHighlight.observerDefault) {
  97690. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97691. }
  97692. delete this._meshes[mesh.uniqueId];
  97693. }
  97694. this._shouldRender = false;
  97695. for (var meshHighlightToCheck in this._meshes) {
  97696. if (this._meshes[meshHighlightToCheck]) {
  97697. this._shouldRender = true;
  97698. break;
  97699. }
  97700. }
  97701. };
  97702. /**
  97703. * Force the stencil to the normal expected value for none glowing parts
  97704. */
  97705. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97706. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97707. };
  97708. /**
  97709. * Free any resources and references associated to a mesh.
  97710. * Internal use
  97711. * @param mesh The mesh to free.
  97712. */
  97713. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97714. this.removeMesh(mesh);
  97715. this.removeExcludedMesh(mesh);
  97716. };
  97717. /**
  97718. * Dispose the highlight layer and free resources.
  97719. */
  97720. HighlightLayer.prototype.dispose = function () {
  97721. if (this._meshes) {
  97722. // Clean mesh references
  97723. for (var id in this._meshes) {
  97724. var meshHighlight = this._meshes[id];
  97725. if (meshHighlight && meshHighlight.mesh) {
  97726. if (meshHighlight.observerHighlight) {
  97727. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97728. }
  97729. if (meshHighlight.observerDefault) {
  97730. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97731. }
  97732. }
  97733. }
  97734. this._meshes = null;
  97735. }
  97736. if (this._excludedMeshes) {
  97737. for (var id in this._excludedMeshes) {
  97738. var meshHighlight = this._excludedMeshes[id];
  97739. if (meshHighlight) {
  97740. if (meshHighlight.beforeRender) {
  97741. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97742. }
  97743. if (meshHighlight.afterRender) {
  97744. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97745. }
  97746. }
  97747. }
  97748. this._excludedMeshes = null;
  97749. }
  97750. _super.prototype.dispose.call(this);
  97751. };
  97752. /**
  97753. * Gets the class name of the effect layer
  97754. * @returns the string with the class name of the effect layer
  97755. */
  97756. HighlightLayer.prototype.getClassName = function () {
  97757. return "HighlightLayer";
  97758. };
  97759. /**
  97760. * Serializes this Highlight layer
  97761. * @returns a serialized Highlight layer object
  97762. */
  97763. HighlightLayer.prototype.serialize = function () {
  97764. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97765. serializationObject.customType = "BABYLON.HighlightLayer";
  97766. // Highlighted meshes
  97767. serializationObject.meshes = [];
  97768. if (this._meshes) {
  97769. for (var m in this._meshes) {
  97770. var mesh = this._meshes[m];
  97771. if (mesh) {
  97772. serializationObject.meshes.push({
  97773. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97774. color: mesh.color.asArray(),
  97775. meshId: mesh.mesh.id
  97776. });
  97777. }
  97778. }
  97779. }
  97780. // Excluded meshes
  97781. serializationObject.excludedMeshes = [];
  97782. if (this._excludedMeshes) {
  97783. for (var e in this._excludedMeshes) {
  97784. var excludedMesh = this._excludedMeshes[e];
  97785. if (excludedMesh) {
  97786. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97787. }
  97788. }
  97789. }
  97790. return serializationObject;
  97791. };
  97792. /**
  97793. * Creates a Highlight layer from parsed Highlight layer data
  97794. * @param parsedHightlightLayer defines the Highlight layer data
  97795. * @param scene defines the current scene
  97796. * @param rootUrl defines the root URL containing the Highlight layer information
  97797. * @returns a parsed Highlight layer
  97798. */
  97799. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97800. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97801. var index;
  97802. // Excluded meshes
  97803. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97804. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97805. if (mesh) {
  97806. hl.addExcludedMesh(mesh);
  97807. }
  97808. }
  97809. // Included meshes
  97810. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97811. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97812. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97813. if (mesh) {
  97814. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97815. }
  97816. }
  97817. return hl;
  97818. };
  97819. /**
  97820. * Effect Name of the highlight layer.
  97821. */
  97822. HighlightLayer.EffectName = "HighlightLayer";
  97823. /**
  97824. * The neutral color used during the preparation of the glow effect.
  97825. * This is black by default as the blend operation is a blend operation.
  97826. */
  97827. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97828. /**
  97829. * Stencil value used for glowing meshes.
  97830. */
  97831. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97832. /**
  97833. * Stencil value used for the other meshes in the scene.
  97834. */
  97835. HighlightLayer.NormalMeshStencilReference = 0x01;
  97836. __decorate([
  97837. BABYLON.serialize()
  97838. ], HighlightLayer.prototype, "innerGlow", void 0);
  97839. __decorate([
  97840. BABYLON.serialize()
  97841. ], HighlightLayer.prototype, "outerGlow", void 0);
  97842. __decorate([
  97843. BABYLON.serialize()
  97844. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97845. __decorate([
  97846. BABYLON.serialize()
  97847. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97848. __decorate([
  97849. BABYLON.serialize("options")
  97850. ], HighlightLayer.prototype, "_options", void 0);
  97851. return HighlightLayer;
  97852. }(BABYLON.EffectLayer));
  97853. BABYLON.HighlightLayer = HighlightLayer;
  97854. })(BABYLON || (BABYLON = {}));
  97855. //# sourceMappingURL=babylon.highlightLayer.js.map
  97856. var BABYLON;
  97857. (function (BABYLON) {
  97858. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97859. for (var index = 0; index < this.effectLayers.length; index++) {
  97860. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97861. return this.effectLayers[index];
  97862. }
  97863. }
  97864. return null;
  97865. };
  97866. /**
  97867. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97868. *
  97869. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97870. * glowy meshes to your scene.
  97871. *
  97872. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97873. */
  97874. var GlowLayer = /** @class */ (function (_super) {
  97875. __extends(GlowLayer, _super);
  97876. /**
  97877. * Instantiates a new glow Layer and references it to the scene.
  97878. * @param name The name of the layer
  97879. * @param scene The scene to use the layer in
  97880. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97881. */
  97882. function GlowLayer(name, scene, options) {
  97883. var _this = _super.call(this, name, scene) || this;
  97884. _this._intensity = 1.0;
  97885. _this._includedOnlyMeshes = [];
  97886. _this._excludedMeshes = [];
  97887. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97888. // Adapt options
  97889. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97890. // Initialize the layer
  97891. _this._init({
  97892. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97893. camera: _this._options.camera,
  97894. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97895. mainTextureRatio: _this._options.mainTextureRatio,
  97896. renderingGroupId: _this._options.renderingGroupId
  97897. });
  97898. return _this;
  97899. }
  97900. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97901. /**
  97902. * Gets the kernel size of the blur.
  97903. */
  97904. get: function () {
  97905. return this._horizontalBlurPostprocess1.kernel;
  97906. },
  97907. /**
  97908. * Sets the kernel size of the blur.
  97909. */
  97910. set: function (value) {
  97911. this._horizontalBlurPostprocess1.kernel = value;
  97912. this._verticalBlurPostprocess1.kernel = value;
  97913. this._horizontalBlurPostprocess2.kernel = value;
  97914. this._verticalBlurPostprocess2.kernel = value;
  97915. },
  97916. enumerable: true,
  97917. configurable: true
  97918. });
  97919. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97920. /**
  97921. * Gets the glow intensity.
  97922. */
  97923. get: function () {
  97924. return this._intensity;
  97925. },
  97926. /**
  97927. * Sets the glow intensity.
  97928. */
  97929. set: function (value) {
  97930. this._intensity = value;
  97931. },
  97932. enumerable: true,
  97933. configurable: true
  97934. });
  97935. /**
  97936. * Get the effect name of the layer.
  97937. * @return The effect name
  97938. */
  97939. GlowLayer.prototype.getEffectName = function () {
  97940. return GlowLayer.EffectName;
  97941. };
  97942. /**
  97943. * Create the merge effect. This is the shader use to blit the information back
  97944. * to the main canvas at the end of the scene rendering.
  97945. */
  97946. GlowLayer.prototype._createMergeEffect = function () {
  97947. // Effect
  97948. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97949. };
  97950. /**
  97951. * Creates the render target textures and post processes used in the glow layer.
  97952. */
  97953. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97954. var _this = this;
  97955. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97956. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97957. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97958. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97959. var textureType = 0;
  97960. if (this._engine.getCaps().textureHalfFloatRender) {
  97961. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97962. }
  97963. else {
  97964. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97965. }
  97966. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97967. width: blurTextureWidth,
  97968. height: blurTextureHeight
  97969. }, this._scene, false, true, textureType);
  97970. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97971. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97972. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97973. this._blurTexture1.renderParticles = false;
  97974. this._blurTexture1.ignoreCameraViewport = true;
  97975. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97976. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97977. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97978. width: blurTextureWidth2,
  97979. height: blurTextureHeight2
  97980. }, this._scene, false, true, textureType);
  97981. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97982. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97983. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97984. this._blurTexture2.renderParticles = false;
  97985. this._blurTexture2.ignoreCameraViewport = true;
  97986. this._textures = [this._blurTexture1, this._blurTexture2];
  97987. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97988. width: blurTextureWidth,
  97989. height: blurTextureHeight
  97990. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97991. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97992. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97993. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97994. effect.setTexture("textureSampler", _this._mainTexture);
  97995. });
  97996. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97997. width: blurTextureWidth,
  97998. height: blurTextureHeight
  97999. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98000. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98001. width: blurTextureWidth2,
  98002. height: blurTextureHeight2
  98003. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98004. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  98005. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  98006. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  98007. effect.setTexture("textureSampler", _this._blurTexture1);
  98008. });
  98009. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98010. width: blurTextureWidth2,
  98011. height: blurTextureHeight2
  98012. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98013. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98014. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  98015. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98016. this._mainTexture.samples = this._options.mainTextureSamples;
  98017. this._mainTexture.onAfterUnbindObservable.add(function () {
  98018. var internalTexture = _this._blurTexture1.getInternalTexture();
  98019. if (internalTexture) {
  98020. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  98021. internalTexture = _this._blurTexture2.getInternalTexture();
  98022. if (internalTexture) {
  98023. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  98024. }
  98025. }
  98026. });
  98027. // Prevent autoClear.
  98028. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98029. };
  98030. /**
  98031. * Checks for the readiness of the element composing the layer.
  98032. * @param subMesh the mesh to check for
  98033. * @param useInstances specify wether or not to use instances to render the mesh
  98034. * @param emissiveTexture the associated emissive texture used to generate the glow
  98035. * @return true if ready otherwise, false
  98036. */
  98037. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  98038. var material = subMesh.getMaterial();
  98039. var mesh = subMesh.getRenderingMesh();
  98040. if (!material || !mesh) {
  98041. return false;
  98042. }
  98043. var emissiveTexture = material.emissiveTexture;
  98044. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98045. };
  98046. /**
  98047. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98048. */
  98049. GlowLayer.prototype.needStencil = function () {
  98050. return false;
  98051. };
  98052. /**
  98053. * Implementation specific of rendering the generating effect on the main canvas.
  98054. * @param effect The effect used to render through
  98055. */
  98056. GlowLayer.prototype._internalRender = function (effect) {
  98057. // Texture
  98058. effect.setTexture("textureSampler", this._blurTexture1);
  98059. effect.setTexture("textureSampler2", this._blurTexture2);
  98060. effect.setFloat("offset", this._intensity);
  98061. // Cache
  98062. var engine = this._engine;
  98063. var previousStencilBuffer = engine.getStencilBuffer();
  98064. // Draw order
  98065. engine.setStencilBuffer(false);
  98066. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98067. // Draw order
  98068. engine.setStencilBuffer(previousStencilBuffer);
  98069. };
  98070. /**
  98071. * Sets the required values for both the emissive texture and and the main color.
  98072. */
  98073. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98074. var textureLevel = 1.0;
  98075. if (this.customEmissiveTextureSelector) {
  98076. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  98077. }
  98078. else {
  98079. if (material) {
  98080. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98081. if (this._emissiveTextureAndColor.texture) {
  98082. textureLevel = this._emissiveTextureAndColor.texture.level;
  98083. }
  98084. }
  98085. else {
  98086. this._emissiveTextureAndColor.texture = null;
  98087. }
  98088. }
  98089. if (this.customEmissiveColorSelector) {
  98090. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  98091. }
  98092. else {
  98093. if (material.emissiveColor) {
  98094. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  98095. }
  98096. else {
  98097. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98098. }
  98099. }
  98100. };
  98101. /**
  98102. * Returns true if the mesh should render, otherwise false.
  98103. * @param mesh The mesh to render
  98104. * @returns true if it should render otherwise false
  98105. */
  98106. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  98107. return this.hasMesh(mesh);
  98108. };
  98109. /**
  98110. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  98111. * @param mesh The mesh to exclude from the glow layer
  98112. */
  98113. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  98114. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  98115. this._excludedMeshes.push(mesh.uniqueId);
  98116. }
  98117. };
  98118. /**
  98119. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  98120. * @param mesh The mesh to remove
  98121. */
  98122. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  98123. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  98124. if (index !== -1) {
  98125. this._excludedMeshes.splice(index, 1);
  98126. }
  98127. };
  98128. /**
  98129. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  98130. * @param mesh The mesh to include in the glow layer
  98131. */
  98132. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  98133. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  98134. this._includedOnlyMeshes.push(mesh.uniqueId);
  98135. }
  98136. };
  98137. /**
  98138. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  98139. * @param mesh The mesh to remove
  98140. */
  98141. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  98142. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  98143. if (index !== -1) {
  98144. this._includedOnlyMeshes.splice(index, 1);
  98145. }
  98146. };
  98147. /**
  98148. * Determine if a given mesh will be used in the glow layer
  98149. * @param mesh The mesh to test
  98150. * @returns true if the mesh will be highlighted by the current glow layer
  98151. */
  98152. GlowLayer.prototype.hasMesh = function (mesh) {
  98153. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98154. return false;
  98155. }
  98156. // Included Mesh
  98157. if (this._includedOnlyMeshes.length) {
  98158. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  98159. }
  98160. ;
  98161. // Excluded Mesh
  98162. if (this._excludedMeshes.length) {
  98163. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  98164. }
  98165. ;
  98166. return true;
  98167. };
  98168. /**
  98169. * Free any resources and references associated to a mesh.
  98170. * Internal use
  98171. * @param mesh The mesh to free.
  98172. */
  98173. GlowLayer.prototype._disposeMesh = function (mesh) {
  98174. this.removeIncludedOnlyMesh(mesh);
  98175. this.removeExcludedMesh(mesh);
  98176. };
  98177. /**
  98178. * Gets the class name of the effect layer
  98179. * @returns the string with the class name of the effect layer
  98180. */
  98181. GlowLayer.prototype.getClassName = function () {
  98182. return "GlowLayer";
  98183. };
  98184. /**
  98185. * Serializes this glow layer
  98186. * @returns a serialized glow layer object
  98187. */
  98188. GlowLayer.prototype.serialize = function () {
  98189. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98190. serializationObject.customType = "BABYLON.GlowLayer";
  98191. var index;
  98192. // Included meshes
  98193. serializationObject.includedMeshes = [];
  98194. if (this._includedOnlyMeshes.length) {
  98195. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  98196. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  98197. if (mesh) {
  98198. serializationObject.includedMeshes.push(mesh.id);
  98199. }
  98200. }
  98201. }
  98202. // Excluded meshes
  98203. serializationObject.excludedMeshes = [];
  98204. if (this._excludedMeshes.length) {
  98205. for (index = 0; index < this._excludedMeshes.length; index++) {
  98206. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98207. if (mesh) {
  98208. serializationObject.excludedMeshes.push(mesh.id);
  98209. }
  98210. }
  98211. }
  98212. return serializationObject;
  98213. };
  98214. /**
  98215. * Creates a Glow Layer from parsed glow layer data
  98216. * @param parsedGlowLayer defines glow layer data
  98217. * @param scene defines the current scene
  98218. * @param rootUrl defines the root URL containing the glow layer information
  98219. * @returns a parsed Glow Layer
  98220. */
  98221. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98222. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98223. var index;
  98224. // Excluded meshes
  98225. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98226. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98227. if (mesh) {
  98228. gl.addExcludedMesh(mesh);
  98229. }
  98230. }
  98231. // Included meshes
  98232. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98233. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98234. if (mesh) {
  98235. gl.addIncludedOnlyMesh(mesh);
  98236. }
  98237. }
  98238. return gl;
  98239. };
  98240. /**
  98241. * Effect Name of the layer.
  98242. */
  98243. GlowLayer.EffectName = "GlowLayer";
  98244. /**
  98245. * The default blur kernel size used for the glow.
  98246. */
  98247. GlowLayer.DefaultBlurKernelSize = 32;
  98248. /**
  98249. * The default texture size ratio used for the glow.
  98250. */
  98251. GlowLayer.DefaultTextureRatio = 0.5;
  98252. __decorate([
  98253. BABYLON.serialize()
  98254. ], GlowLayer.prototype, "blurKernelSize", null);
  98255. __decorate([
  98256. BABYLON.serialize()
  98257. ], GlowLayer.prototype, "intensity", null);
  98258. __decorate([
  98259. BABYLON.serialize("options")
  98260. ], GlowLayer.prototype, "_options", void 0);
  98261. return GlowLayer;
  98262. }(BABYLON.EffectLayer));
  98263. BABYLON.GlowLayer = GlowLayer;
  98264. })(BABYLON || (BABYLON = {}));
  98265. //# sourceMappingURL=babylon.glowLayer.js.map
  98266. var BABYLON;
  98267. (function (BABYLON) {
  98268. /**
  98269. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98270. */
  98271. var AssetTaskState;
  98272. (function (AssetTaskState) {
  98273. /**
  98274. * Initialization
  98275. */
  98276. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98277. /**
  98278. * Running
  98279. */
  98280. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98281. /**
  98282. * Done
  98283. */
  98284. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98285. /**
  98286. * Error
  98287. */
  98288. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98289. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98290. /**
  98291. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98292. */
  98293. var AbstractAssetTask = /** @class */ (function () {
  98294. /**
  98295. * Creates a new {BABYLON.AssetsManager}
  98296. * @param name defines the name of the task
  98297. */
  98298. function AbstractAssetTask(
  98299. /**
  98300. * Task name
  98301. */ name) {
  98302. this.name = name;
  98303. this._isCompleted = false;
  98304. this._taskState = AssetTaskState.INIT;
  98305. }
  98306. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98307. /**
  98308. * Get if the task is completed
  98309. */
  98310. get: function () {
  98311. return this._isCompleted;
  98312. },
  98313. enumerable: true,
  98314. configurable: true
  98315. });
  98316. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98317. /**
  98318. * Gets the current state of the task
  98319. */
  98320. get: function () {
  98321. return this._taskState;
  98322. },
  98323. enumerable: true,
  98324. configurable: true
  98325. });
  98326. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98327. /**
  98328. * Gets the current error object (if task is in error)
  98329. */
  98330. get: function () {
  98331. return this._errorObject;
  98332. },
  98333. enumerable: true,
  98334. configurable: true
  98335. });
  98336. /**
  98337. * Internal only
  98338. * @hidden
  98339. */
  98340. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98341. if (this._errorObject) {
  98342. return;
  98343. }
  98344. this._errorObject = {
  98345. message: message,
  98346. exception: exception
  98347. };
  98348. };
  98349. /**
  98350. * Execute the current task
  98351. * @param scene defines the scene where you want your assets to be loaded
  98352. * @param onSuccess is a callback called when the task is successfully executed
  98353. * @param onError is a callback called if an error occurs
  98354. */
  98355. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98356. var _this = this;
  98357. this._taskState = AssetTaskState.RUNNING;
  98358. this.runTask(scene, function () {
  98359. _this.onDoneCallback(onSuccess, onError);
  98360. }, function (msg, exception) {
  98361. _this.onErrorCallback(onError, msg, exception);
  98362. });
  98363. };
  98364. /**
  98365. * Execute the current task
  98366. * @param scene defines the scene where you want your assets to be loaded
  98367. * @param onSuccess is a callback called when the task is successfully executed
  98368. * @param onError is a callback called if an error occurs
  98369. */
  98370. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98371. throw new Error("runTask is not implemented");
  98372. };
  98373. /**
  98374. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98375. * This can be used with failed tasks that have the reason for failure fixed.
  98376. */
  98377. AbstractAssetTask.prototype.reset = function () {
  98378. this._taskState = AssetTaskState.INIT;
  98379. };
  98380. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98381. this._taskState = AssetTaskState.ERROR;
  98382. this._errorObject = {
  98383. message: message,
  98384. exception: exception
  98385. };
  98386. if (this.onError) {
  98387. this.onError(this, message, exception);
  98388. }
  98389. onError();
  98390. };
  98391. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98392. try {
  98393. this._taskState = AssetTaskState.DONE;
  98394. this._isCompleted = true;
  98395. if (this.onSuccess) {
  98396. this.onSuccess(this);
  98397. }
  98398. onSuccess();
  98399. }
  98400. catch (e) {
  98401. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98402. }
  98403. };
  98404. return AbstractAssetTask;
  98405. }());
  98406. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98407. /**
  98408. * Class used to share progress information about assets loading
  98409. */
  98410. var AssetsProgressEvent = /** @class */ (function () {
  98411. /**
  98412. * Creates a {BABYLON.AssetsProgressEvent}
  98413. * @param remainingCount defines the number of remaining tasks to process
  98414. * @param totalCount defines the total number of tasks
  98415. * @param task defines the task that was just processed
  98416. */
  98417. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98418. this.remainingCount = remainingCount;
  98419. this.totalCount = totalCount;
  98420. this.task = task;
  98421. }
  98422. return AssetsProgressEvent;
  98423. }());
  98424. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98425. /**
  98426. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98427. */
  98428. var MeshAssetTask = /** @class */ (function (_super) {
  98429. __extends(MeshAssetTask, _super);
  98430. /**
  98431. * Creates a new {BABYLON.MeshAssetTask}
  98432. * @param name defines the name of the task
  98433. * @param meshesNames defines the list of mesh's names you want to load
  98434. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98435. * @param sceneFilename defines the filename of the scene to load from
  98436. */
  98437. function MeshAssetTask(
  98438. /**
  98439. * Defines the name of the task
  98440. */
  98441. name,
  98442. /**
  98443. * Defines the list of mesh's names you want to load
  98444. */
  98445. meshesNames,
  98446. /**
  98447. * Defines the root url to use as a base to load your meshes and associated resources
  98448. */
  98449. rootUrl,
  98450. /**
  98451. * Defines the filename of the scene to load from
  98452. */
  98453. sceneFilename) {
  98454. var _this = _super.call(this, name) || this;
  98455. _this.name = name;
  98456. _this.meshesNames = meshesNames;
  98457. _this.rootUrl = rootUrl;
  98458. _this.sceneFilename = sceneFilename;
  98459. return _this;
  98460. }
  98461. /**
  98462. * Execute the current task
  98463. * @param scene defines the scene where you want your assets to be loaded
  98464. * @param onSuccess is a callback called when the task is successfully executed
  98465. * @param onError is a callback called if an error occurs
  98466. */
  98467. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98468. var _this = this;
  98469. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98470. _this.loadedMeshes = meshes;
  98471. _this.loadedParticleSystems = particleSystems;
  98472. _this.loadedSkeletons = skeletons;
  98473. onSuccess();
  98474. }, null, function (scene, message, exception) {
  98475. onError(message, exception);
  98476. });
  98477. };
  98478. return MeshAssetTask;
  98479. }(AbstractAssetTask));
  98480. BABYLON.MeshAssetTask = MeshAssetTask;
  98481. /**
  98482. * Define a task used by {BABYLON.AssetsManager} to load text content
  98483. */
  98484. var TextFileAssetTask = /** @class */ (function (_super) {
  98485. __extends(TextFileAssetTask, _super);
  98486. /**
  98487. * Creates a new TextFileAssetTask object
  98488. * @param name defines the name of the task
  98489. * @param url defines the location of the file to load
  98490. */
  98491. function TextFileAssetTask(
  98492. /**
  98493. * Defines the name of the task
  98494. */
  98495. name,
  98496. /**
  98497. * Defines the location of the file to load
  98498. */
  98499. url) {
  98500. var _this = _super.call(this, name) || this;
  98501. _this.name = name;
  98502. _this.url = url;
  98503. return _this;
  98504. }
  98505. /**
  98506. * Execute the current task
  98507. * @param scene defines the scene where you want your assets to be loaded
  98508. * @param onSuccess is a callback called when the task is successfully executed
  98509. * @param onError is a callback called if an error occurs
  98510. */
  98511. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98512. var _this = this;
  98513. scene._loadFile(this.url, function (data) {
  98514. _this.text = data;
  98515. onSuccess();
  98516. }, undefined, false, false, function (request, exception) {
  98517. if (request) {
  98518. onError(request.status + " " + request.statusText, exception);
  98519. }
  98520. });
  98521. };
  98522. return TextFileAssetTask;
  98523. }(AbstractAssetTask));
  98524. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98525. /**
  98526. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98527. */
  98528. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98529. __extends(BinaryFileAssetTask, _super);
  98530. /**
  98531. * Creates a new BinaryFileAssetTask object
  98532. * @param name defines the name of the new task
  98533. * @param url defines the location of the file to load
  98534. */
  98535. function BinaryFileAssetTask(
  98536. /**
  98537. * Defines the name of the task
  98538. */
  98539. name,
  98540. /**
  98541. * Defines the location of the file to load
  98542. */
  98543. url) {
  98544. var _this = _super.call(this, name) || this;
  98545. _this.name = name;
  98546. _this.url = url;
  98547. return _this;
  98548. }
  98549. /**
  98550. * Execute the current task
  98551. * @param scene defines the scene where you want your assets to be loaded
  98552. * @param onSuccess is a callback called when the task is successfully executed
  98553. * @param onError is a callback called if an error occurs
  98554. */
  98555. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98556. var _this = this;
  98557. scene._loadFile(this.url, function (data) {
  98558. _this.data = data;
  98559. onSuccess();
  98560. }, undefined, true, true, function (request, exception) {
  98561. if (request) {
  98562. onError(request.status + " " + request.statusText, exception);
  98563. }
  98564. });
  98565. };
  98566. return BinaryFileAssetTask;
  98567. }(AbstractAssetTask));
  98568. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98569. /**
  98570. * Define a task used by {BABYLON.AssetsManager} to load images
  98571. */
  98572. var ImageAssetTask = /** @class */ (function (_super) {
  98573. __extends(ImageAssetTask, _super);
  98574. /**
  98575. * Creates a new ImageAssetTask
  98576. * @param name defines the name of the task
  98577. * @param url defines the location of the image to load
  98578. */
  98579. function ImageAssetTask(
  98580. /**
  98581. * Defines the name of the task
  98582. */
  98583. name,
  98584. /**
  98585. * Defines the location of the image to load
  98586. */
  98587. url) {
  98588. var _this = _super.call(this, name) || this;
  98589. _this.name = name;
  98590. _this.url = url;
  98591. return _this;
  98592. }
  98593. /**
  98594. * Execute the current task
  98595. * @param scene defines the scene where you want your assets to be loaded
  98596. * @param onSuccess is a callback called when the task is successfully executed
  98597. * @param onError is a callback called if an error occurs
  98598. */
  98599. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98600. var _this = this;
  98601. var img = new Image();
  98602. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98603. img.onload = function () {
  98604. _this.image = img;
  98605. onSuccess();
  98606. };
  98607. img.onerror = function (err) {
  98608. onError("Error loading image", err);
  98609. };
  98610. img.src = this.url;
  98611. };
  98612. return ImageAssetTask;
  98613. }(AbstractAssetTask));
  98614. BABYLON.ImageAssetTask = ImageAssetTask;
  98615. /**
  98616. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98617. */
  98618. var TextureAssetTask = /** @class */ (function (_super) {
  98619. __extends(TextureAssetTask, _super);
  98620. /**
  98621. * Creates a new TextureAssetTask object
  98622. * @param name defines the name of the task
  98623. * @param url defines the location of the file to load
  98624. * @param noMipmap defines if mipmap should not be generated (default is false)
  98625. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98626. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98627. */
  98628. function TextureAssetTask(
  98629. /**
  98630. * Defines the name of the task
  98631. */
  98632. name,
  98633. /**
  98634. * Defines the location of the file to load
  98635. */
  98636. url,
  98637. /**
  98638. * Defines if mipmap should not be generated (default is false)
  98639. */
  98640. noMipmap,
  98641. /**
  98642. * Defines if texture must be inverted on Y axis (default is false)
  98643. */
  98644. invertY,
  98645. /**
  98646. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98647. */
  98648. samplingMode) {
  98649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98650. var _this = _super.call(this, name) || this;
  98651. _this.name = name;
  98652. _this.url = url;
  98653. _this.noMipmap = noMipmap;
  98654. _this.invertY = invertY;
  98655. _this.samplingMode = samplingMode;
  98656. return _this;
  98657. }
  98658. /**
  98659. * Execute the current task
  98660. * @param scene defines the scene where you want your assets to be loaded
  98661. * @param onSuccess is a callback called when the task is successfully executed
  98662. * @param onError is a callback called if an error occurs
  98663. */
  98664. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98665. var onload = function () {
  98666. onSuccess();
  98667. };
  98668. var onerror = function (message, exception) {
  98669. onError(message, exception);
  98670. };
  98671. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98672. };
  98673. return TextureAssetTask;
  98674. }(AbstractAssetTask));
  98675. BABYLON.TextureAssetTask = TextureAssetTask;
  98676. /**
  98677. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98678. */
  98679. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98680. __extends(CubeTextureAssetTask, _super);
  98681. /**
  98682. * Creates a new CubeTextureAssetTask
  98683. * @param name defines the name of the task
  98684. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98685. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98686. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98687. * @param files defines the explicit list of files (undefined by default)
  98688. */
  98689. function CubeTextureAssetTask(
  98690. /**
  98691. * Defines the name of the task
  98692. */
  98693. name,
  98694. /**
  98695. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98696. */
  98697. url,
  98698. /**
  98699. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98700. */
  98701. extensions,
  98702. /**
  98703. * Defines if mipmaps should not be generated (default is false)
  98704. */
  98705. noMipmap,
  98706. /**
  98707. * Defines the explicit list of files (undefined by default)
  98708. */
  98709. files) {
  98710. var _this = _super.call(this, name) || this;
  98711. _this.name = name;
  98712. _this.url = url;
  98713. _this.extensions = extensions;
  98714. _this.noMipmap = noMipmap;
  98715. _this.files = files;
  98716. return _this;
  98717. }
  98718. /**
  98719. * Execute the current task
  98720. * @param scene defines the scene where you want your assets to be loaded
  98721. * @param onSuccess is a callback called when the task is successfully executed
  98722. * @param onError is a callback called if an error occurs
  98723. */
  98724. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98725. var onload = function () {
  98726. onSuccess();
  98727. };
  98728. var onerror = function (message, exception) {
  98729. onError(message, exception);
  98730. };
  98731. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98732. };
  98733. return CubeTextureAssetTask;
  98734. }(AbstractAssetTask));
  98735. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98736. /**
  98737. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98738. */
  98739. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98740. __extends(HDRCubeTextureAssetTask, _super);
  98741. /**
  98742. * Creates a new HDRCubeTextureAssetTask object
  98743. * @param name defines the name of the task
  98744. * @param url defines the location of the file to load
  98745. * @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.
  98746. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98747. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98748. * @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)
  98749. * @param reserved Internal use only
  98750. */
  98751. function HDRCubeTextureAssetTask(
  98752. /**
  98753. * Defines the name of the task
  98754. */
  98755. name,
  98756. /**
  98757. * Defines the location of the file to load
  98758. */
  98759. url,
  98760. /**
  98761. * Defines the desired size (the more it increases the longer the generation will be)
  98762. */
  98763. size,
  98764. /**
  98765. * Defines if mipmaps should not be generated (default is false)
  98766. */
  98767. noMipmap,
  98768. /**
  98769. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98770. */
  98771. generateHarmonics,
  98772. /**
  98773. * 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)
  98774. */
  98775. gammaSpace,
  98776. /**
  98777. * Internal Use Only
  98778. */
  98779. reserved) {
  98780. if (noMipmap === void 0) { noMipmap = false; }
  98781. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98782. if (gammaSpace === void 0) { gammaSpace = false; }
  98783. if (reserved === void 0) { reserved = false; }
  98784. var _this = _super.call(this, name) || this;
  98785. _this.name = name;
  98786. _this.url = url;
  98787. _this.size = size;
  98788. _this.noMipmap = noMipmap;
  98789. _this.generateHarmonics = generateHarmonics;
  98790. _this.gammaSpace = gammaSpace;
  98791. _this.reserved = reserved;
  98792. return _this;
  98793. }
  98794. /**
  98795. * Execute the current task
  98796. * @param scene defines the scene where you want your assets to be loaded
  98797. * @param onSuccess is a callback called when the task is successfully executed
  98798. * @param onError is a callback called if an error occurs
  98799. */
  98800. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98801. var onload = function () {
  98802. onSuccess();
  98803. };
  98804. var onerror = function (message, exception) {
  98805. onError(message, exception);
  98806. };
  98807. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98808. };
  98809. return HDRCubeTextureAssetTask;
  98810. }(AbstractAssetTask));
  98811. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98812. /**
  98813. * This class can be used to easily import assets into a scene
  98814. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98815. */
  98816. var AssetsManager = /** @class */ (function () {
  98817. /**
  98818. * Creates a new AssetsManager
  98819. * @param scene defines the scene to work on
  98820. */
  98821. function AssetsManager(scene) {
  98822. this._isLoading = false;
  98823. this._tasks = new Array();
  98824. this._waitingTasksCount = 0;
  98825. this._totalTasksCount = 0;
  98826. /**
  98827. * Observable called when all tasks are processed
  98828. */
  98829. this.onTaskSuccessObservable = new BABYLON.Observable();
  98830. /**
  98831. * Observable called when a task had an error
  98832. */
  98833. this.onTaskErrorObservable = new BABYLON.Observable();
  98834. /**
  98835. * Observable called when a task is successful
  98836. */
  98837. this.onTasksDoneObservable = new BABYLON.Observable();
  98838. /**
  98839. * Observable called when a task is done (whatever the result is)
  98840. */
  98841. this.onProgressObservable = new BABYLON.Observable();
  98842. /**
  98843. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98844. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98845. */
  98846. this.useDefaultLoadingScreen = true;
  98847. this._scene = scene;
  98848. }
  98849. /**
  98850. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98851. * @param taskName defines the name of the new task
  98852. * @param meshesNames defines the name of meshes to load
  98853. * @param rootUrl defines the root url to use to locate files
  98854. * @param sceneFilename defines the filename of the scene file
  98855. * @returns a new {BABYLON.MeshAssetTask} object
  98856. */
  98857. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98858. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98859. this._tasks.push(task);
  98860. return task;
  98861. };
  98862. /**
  98863. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98864. * @param taskName defines the name of the new task
  98865. * @param url defines the url of the file to load
  98866. * @returns a new {BABYLON.TextFileAssetTask} object
  98867. */
  98868. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98869. var task = new TextFileAssetTask(taskName, url);
  98870. this._tasks.push(task);
  98871. return task;
  98872. };
  98873. /**
  98874. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98875. * @param taskName defines the name of the new task
  98876. * @param url defines the url of the file to load
  98877. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98878. */
  98879. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98880. var task = new BinaryFileAssetTask(taskName, url);
  98881. this._tasks.push(task);
  98882. return task;
  98883. };
  98884. /**
  98885. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98886. * @param taskName defines the name of the new task
  98887. * @param url defines the url of the file to load
  98888. * @returns a new {BABYLON.ImageAssetTask} object
  98889. */
  98890. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98891. var task = new ImageAssetTask(taskName, url);
  98892. this._tasks.push(task);
  98893. return task;
  98894. };
  98895. /**
  98896. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98897. * @param taskName defines the name of the new task
  98898. * @param url defines the url of the file to load
  98899. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98900. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98901. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98902. * @returns a new {BABYLON.TextureAssetTask} object
  98903. */
  98904. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98906. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98907. this._tasks.push(task);
  98908. return task;
  98909. };
  98910. /**
  98911. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98912. * @param taskName defines the name of the new task
  98913. * @param url defines the url of the file to load
  98914. * @param extensions defines the extension to use to load the cube map (can be null)
  98915. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98916. * @param files defines the list of files to load (can be null)
  98917. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98918. */
  98919. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98920. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98921. this._tasks.push(task);
  98922. return task;
  98923. };
  98924. /**
  98925. *
  98926. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98927. * @param taskName defines the name of the new task
  98928. * @param url defines the url of the file to load
  98929. * @param size defines the size you want for the cubemap (can be null)
  98930. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98931. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98932. * @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)
  98933. * @param reserved Internal use only
  98934. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98935. */
  98936. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98937. if (noMipmap === void 0) { noMipmap = false; }
  98938. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98939. if (gammaSpace === void 0) { gammaSpace = false; }
  98940. if (reserved === void 0) { reserved = false; }
  98941. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98942. this._tasks.push(task);
  98943. return task;
  98944. };
  98945. /**
  98946. * Remove a task from the assets manager.
  98947. * @param task the task to remove
  98948. */
  98949. AssetsManager.prototype.removeTask = function (task) {
  98950. var index = this._tasks.indexOf(task);
  98951. if (index > -1) {
  98952. this._tasks.splice(index, 1);
  98953. }
  98954. };
  98955. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98956. this._waitingTasksCount--;
  98957. try {
  98958. if (this.onProgress) {
  98959. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98960. }
  98961. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98962. }
  98963. catch (e) {
  98964. BABYLON.Tools.Error("Error running progress callbacks.");
  98965. console.log(e);
  98966. }
  98967. if (this._waitingTasksCount === 0) {
  98968. try {
  98969. if (this.onFinish) {
  98970. this.onFinish(this._tasks);
  98971. }
  98972. // Let's remove successfull tasks
  98973. var currentTasks = this._tasks.slice();
  98974. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98975. var task = currentTasks_1[_i];
  98976. if (task.taskState === AssetTaskState.DONE) {
  98977. var index = this._tasks.indexOf(task);
  98978. if (index > -1) {
  98979. this._tasks.splice(index, 1);
  98980. }
  98981. }
  98982. }
  98983. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98984. }
  98985. catch (e) {
  98986. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98987. console.log(e);
  98988. }
  98989. this._isLoading = false;
  98990. this._scene.getEngine().hideLoadingUI();
  98991. }
  98992. };
  98993. AssetsManager.prototype._runTask = function (task) {
  98994. var _this = this;
  98995. var done = function () {
  98996. try {
  98997. if (_this.onTaskSuccess) {
  98998. _this.onTaskSuccess(task);
  98999. }
  99000. _this.onTaskSuccessObservable.notifyObservers(task);
  99001. _this._decreaseWaitingTasksCount(task);
  99002. }
  99003. catch (e) {
  99004. error("Error executing task success callbacks", e);
  99005. }
  99006. };
  99007. var error = function (message, exception) {
  99008. task._setErrorObject(message, exception);
  99009. if (_this.onTaskError) {
  99010. _this.onTaskError(task);
  99011. }
  99012. _this.onTaskErrorObservable.notifyObservers(task);
  99013. _this._decreaseWaitingTasksCount(task);
  99014. };
  99015. task.run(this._scene, done, error);
  99016. };
  99017. /**
  99018. * Reset the {BABYLON.AssetsManager} and remove all tasks
  99019. * @return the current instance of the {BABYLON.AssetsManager}
  99020. */
  99021. AssetsManager.prototype.reset = function () {
  99022. this._isLoading = false;
  99023. this._tasks = new Array();
  99024. return this;
  99025. };
  99026. /**
  99027. * Start the loading process
  99028. * @return the current instance of the {BABYLON.AssetsManager}
  99029. */
  99030. AssetsManager.prototype.load = function () {
  99031. if (this._isLoading) {
  99032. return this;
  99033. }
  99034. this._isLoading = true;
  99035. this._waitingTasksCount = this._tasks.length;
  99036. this._totalTasksCount = this._tasks.length;
  99037. if (this._waitingTasksCount === 0) {
  99038. this._isLoading = false;
  99039. if (this.onFinish) {
  99040. this.onFinish(this._tasks);
  99041. }
  99042. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99043. return this;
  99044. }
  99045. if (this.useDefaultLoadingScreen) {
  99046. this._scene.getEngine().displayLoadingUI();
  99047. }
  99048. for (var index = 0; index < this._tasks.length; index++) {
  99049. var task = this._tasks[index];
  99050. if (task.taskState === AssetTaskState.INIT) {
  99051. this._runTask(task);
  99052. }
  99053. }
  99054. return this;
  99055. };
  99056. return AssetsManager;
  99057. }());
  99058. BABYLON.AssetsManager = AssetsManager;
  99059. })(BABYLON || (BABYLON = {}));
  99060. //# sourceMappingURL=babylon.assetsManager.js.map
  99061. var BABYLON;
  99062. (function (BABYLON) {
  99063. var serializedGeometries = [];
  99064. var serializeGeometry = function (geometry, serializationGeometries) {
  99065. if (serializedGeometries[geometry.id]) {
  99066. return;
  99067. }
  99068. if (geometry.doNotSerialize) {
  99069. return;
  99070. }
  99071. if (geometry instanceof BABYLON.BoxGeometry) {
  99072. serializationGeometries.boxes.push(geometry.serialize());
  99073. }
  99074. else if (geometry instanceof BABYLON.SphereGeometry) {
  99075. serializationGeometries.spheres.push(geometry.serialize());
  99076. }
  99077. else if (geometry instanceof BABYLON.CylinderGeometry) {
  99078. serializationGeometries.cylinders.push(geometry.serialize());
  99079. }
  99080. else if (geometry instanceof BABYLON.TorusGeometry) {
  99081. serializationGeometries.toruses.push(geometry.serialize());
  99082. }
  99083. else if (geometry instanceof BABYLON.GroundGeometry) {
  99084. serializationGeometries.grounds.push(geometry.serialize());
  99085. }
  99086. else if (geometry instanceof BABYLON.Plane) {
  99087. serializationGeometries.planes.push(geometry.serialize());
  99088. }
  99089. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  99090. serializationGeometries.torusKnots.push(geometry.serialize());
  99091. }
  99092. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  99093. throw new Error("Unknown primitive type");
  99094. }
  99095. else {
  99096. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  99097. }
  99098. serializedGeometries[geometry.id] = true;
  99099. };
  99100. var serializeMesh = function (mesh, serializationScene) {
  99101. var serializationObject = {};
  99102. // Geometry
  99103. var geometry = mesh._geometry;
  99104. if (geometry) {
  99105. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  99106. // 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
  99107. serializeGeometry(geometry, serializationScene.geometries);
  99108. }
  99109. }
  99110. // Custom
  99111. if (mesh.serialize) {
  99112. mesh.serialize(serializationObject);
  99113. }
  99114. return serializationObject;
  99115. };
  99116. var finalizeSingleMesh = function (mesh, serializationObject) {
  99117. //only works if the mesh is already loaded
  99118. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99119. //serialize material
  99120. if (mesh.material) {
  99121. if (mesh.material instanceof BABYLON.MultiMaterial) {
  99122. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  99123. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99124. serializationObject.multiMaterials.push(mesh.material.serialize());
  99125. }
  99126. }
  99127. else {
  99128. serializationObject.materials = serializationObject.materials || [];
  99129. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99130. serializationObject.materials.push(mesh.material.serialize());
  99131. }
  99132. }
  99133. }
  99134. //serialize geometry
  99135. var geometry = mesh._geometry;
  99136. if (geometry) {
  99137. if (!serializationObject.geometries) {
  99138. serializationObject.geometries = {};
  99139. serializationObject.geometries.boxes = [];
  99140. serializationObject.geometries.spheres = [];
  99141. serializationObject.geometries.cylinders = [];
  99142. serializationObject.geometries.toruses = [];
  99143. serializationObject.geometries.grounds = [];
  99144. serializationObject.geometries.planes = [];
  99145. serializationObject.geometries.torusKnots = [];
  99146. serializationObject.geometries.vertexData = [];
  99147. }
  99148. serializeGeometry(geometry, serializationObject.geometries);
  99149. }
  99150. // Skeletons
  99151. if (mesh.skeleton) {
  99152. serializationObject.skeletons = serializationObject.skeletons || [];
  99153. serializationObject.skeletons.push(mesh.skeleton.serialize());
  99154. }
  99155. //serialize the actual mesh
  99156. serializationObject.meshes = serializationObject.meshes || [];
  99157. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99158. }
  99159. };
  99160. var SceneSerializer = /** @class */ (function () {
  99161. function SceneSerializer() {
  99162. }
  99163. SceneSerializer.ClearCache = function () {
  99164. serializedGeometries = [];
  99165. };
  99166. SceneSerializer.Serialize = function (scene) {
  99167. var serializationObject = {};
  99168. SceneSerializer.ClearCache();
  99169. // Scene
  99170. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  99171. serializationObject.autoClear = scene.autoClear;
  99172. serializationObject.clearColor = scene.clearColor.asArray();
  99173. serializationObject.ambientColor = scene.ambientColor.asArray();
  99174. serializationObject.gravity = scene.gravity.asArray();
  99175. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  99176. serializationObject.workerCollisions = scene.workerCollisions;
  99177. // Fog
  99178. if (scene.fogMode && scene.fogMode !== 0) {
  99179. serializationObject.fogMode = scene.fogMode;
  99180. serializationObject.fogColor = scene.fogColor.asArray();
  99181. serializationObject.fogStart = scene.fogStart;
  99182. serializationObject.fogEnd = scene.fogEnd;
  99183. serializationObject.fogDensity = scene.fogDensity;
  99184. }
  99185. //Physics
  99186. if (scene.isPhysicsEnabled()) {
  99187. var physicEngine = scene.getPhysicsEngine();
  99188. if (physicEngine) {
  99189. serializationObject.physicsEnabled = true;
  99190. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  99191. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  99192. }
  99193. }
  99194. // Metadata
  99195. if (scene.metadata) {
  99196. serializationObject.metadata = scene.metadata;
  99197. }
  99198. // Morph targets
  99199. serializationObject.morphTargetManagers = [];
  99200. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99201. var abstractMesh = _a[_i];
  99202. var manager = abstractMesh.morphTargetManager;
  99203. if (manager) {
  99204. serializationObject.morphTargetManagers.push(manager.serialize());
  99205. }
  99206. }
  99207. // Lights
  99208. serializationObject.lights = [];
  99209. var index;
  99210. var light;
  99211. for (index = 0; index < scene.lights.length; index++) {
  99212. light = scene.lights[index];
  99213. if (!light.doNotSerialize) {
  99214. serializationObject.lights.push(light.serialize());
  99215. }
  99216. }
  99217. // Cameras
  99218. serializationObject.cameras = [];
  99219. for (index = 0; index < scene.cameras.length; index++) {
  99220. var camera = scene.cameras[index];
  99221. if (!camera.doNotSerialize) {
  99222. serializationObject.cameras.push(camera.serialize());
  99223. }
  99224. }
  99225. if (scene.activeCamera) {
  99226. serializationObject.activeCameraID = scene.activeCamera.id;
  99227. }
  99228. // Animations
  99229. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99230. // Materials
  99231. serializationObject.materials = [];
  99232. serializationObject.multiMaterials = [];
  99233. var material;
  99234. for (index = 0; index < scene.materials.length; index++) {
  99235. material = scene.materials[index];
  99236. if (!material.doNotSerialize) {
  99237. serializationObject.materials.push(material.serialize());
  99238. }
  99239. }
  99240. // MultiMaterials
  99241. serializationObject.multiMaterials = [];
  99242. for (index = 0; index < scene.multiMaterials.length; index++) {
  99243. var multiMaterial = scene.multiMaterials[index];
  99244. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99245. }
  99246. // Environment texture
  99247. if (scene.environmentTexture) {
  99248. serializationObject.environmentTexture = scene.environmentTexture.name;
  99249. }
  99250. // Skeletons
  99251. serializationObject.skeletons = [];
  99252. for (index = 0; index < scene.skeletons.length; index++) {
  99253. var skeleton = scene.skeletons[index];
  99254. if (!skeleton.doNotSerialize) {
  99255. serializationObject.skeletons.push(skeleton.serialize());
  99256. }
  99257. }
  99258. // Transform nodes
  99259. serializationObject.transformNodes = [];
  99260. for (index = 0; index < scene.transformNodes.length; index++) {
  99261. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99262. }
  99263. // Geometries
  99264. serializationObject.geometries = {};
  99265. serializationObject.geometries.boxes = [];
  99266. serializationObject.geometries.spheres = [];
  99267. serializationObject.geometries.cylinders = [];
  99268. serializationObject.geometries.toruses = [];
  99269. serializationObject.geometries.grounds = [];
  99270. serializationObject.geometries.planes = [];
  99271. serializationObject.geometries.torusKnots = [];
  99272. serializationObject.geometries.vertexData = [];
  99273. serializedGeometries = [];
  99274. var geometries = scene.getGeometries();
  99275. for (index = 0; index < geometries.length; index++) {
  99276. var geometry = geometries[index];
  99277. if (geometry.isReady()) {
  99278. serializeGeometry(geometry, serializationObject.geometries);
  99279. }
  99280. }
  99281. // Meshes
  99282. serializationObject.meshes = [];
  99283. for (index = 0; index < scene.meshes.length; index++) {
  99284. var abstractMesh = scene.meshes[index];
  99285. if (abstractMesh instanceof BABYLON.Mesh) {
  99286. var mesh = abstractMesh;
  99287. if (!mesh.doNotSerialize) {
  99288. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99289. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99290. }
  99291. }
  99292. }
  99293. }
  99294. // Particles Systems
  99295. serializationObject.particleSystems = [];
  99296. for (index = 0; index < scene.particleSystems.length; index++) {
  99297. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99298. }
  99299. // Shadows
  99300. serializationObject.shadowGenerators = [];
  99301. for (index = 0; index < scene.lights.length; index++) {
  99302. light = scene.lights[index];
  99303. var shadowGenerator = light.getShadowGenerator();
  99304. if (shadowGenerator) {
  99305. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99306. }
  99307. }
  99308. // Action Manager
  99309. if (scene.actionManager) {
  99310. serializationObject.actions = scene.actionManager.serialize("scene");
  99311. }
  99312. // Audio
  99313. serializationObject.sounds = [];
  99314. for (index = 0; index < scene.soundTracks.length; index++) {
  99315. var soundtrack = scene.soundTracks[index];
  99316. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99317. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99318. }
  99319. }
  99320. // Components
  99321. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99322. var component = _c[_b];
  99323. component.serialize(serializationObject);
  99324. }
  99325. return serializationObject;
  99326. };
  99327. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99328. if (withParents === void 0) { withParents = false; }
  99329. if (withChildren === void 0) { withChildren = false; }
  99330. var serializationObject = {};
  99331. SceneSerializer.ClearCache();
  99332. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99333. if (withParents || withChildren) {
  99334. //deliberate for loop! not for each, appended should be processed as well.
  99335. for (var i = 0; i < toSerialize.length; ++i) {
  99336. if (withChildren) {
  99337. toSerialize[i].getDescendants().forEach(function (node) {
  99338. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99339. toSerialize.push(node);
  99340. }
  99341. });
  99342. }
  99343. //make sure the array doesn't contain the object already
  99344. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99345. toSerialize.push(toSerialize[i].parent);
  99346. }
  99347. }
  99348. }
  99349. toSerialize.forEach(function (mesh) {
  99350. finalizeSingleMesh(mesh, serializationObject);
  99351. });
  99352. return serializationObject;
  99353. };
  99354. return SceneSerializer;
  99355. }());
  99356. BABYLON.SceneSerializer = SceneSerializer;
  99357. })(BABYLON || (BABYLON = {}));
  99358. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99359. var BABYLON;
  99360. (function (BABYLON) {
  99361. var ReflectionProbe = /** @class */ (function () {
  99362. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99364. var _this = this;
  99365. this.name = name;
  99366. this._viewMatrix = BABYLON.Matrix.Identity();
  99367. this._target = BABYLON.Vector3.Zero();
  99368. this._add = BABYLON.Vector3.Zero();
  99369. this._invertYAxis = false;
  99370. this.position = BABYLON.Vector3.Zero();
  99371. this._scene = scene;
  99372. this._scene.reflectionProbes.push(this);
  99373. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99374. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99375. switch (faceIndex) {
  99376. case 0:
  99377. _this._add.copyFromFloats(1, 0, 0);
  99378. break;
  99379. case 1:
  99380. _this._add.copyFromFloats(-1, 0, 0);
  99381. break;
  99382. case 2:
  99383. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99384. break;
  99385. case 3:
  99386. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99387. break;
  99388. case 4:
  99389. _this._add.copyFromFloats(0, 0, 1);
  99390. break;
  99391. case 5:
  99392. _this._add.copyFromFloats(0, 0, -1);
  99393. break;
  99394. }
  99395. if (_this._attachedMesh) {
  99396. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99397. }
  99398. _this.position.addToRef(_this._add, _this._target);
  99399. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99400. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99401. scene._forcedViewPosition = _this.position;
  99402. });
  99403. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99404. scene._forcedViewPosition = null;
  99405. scene.updateTransformMatrix(true);
  99406. });
  99407. if (scene.activeCamera) {
  99408. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99409. }
  99410. }
  99411. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99412. get: function () {
  99413. return this._renderTargetTexture.samples;
  99414. },
  99415. set: function (value) {
  99416. this._renderTargetTexture.samples = value;
  99417. },
  99418. enumerable: true,
  99419. configurable: true
  99420. });
  99421. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99422. get: function () {
  99423. return this._renderTargetTexture.refreshRate;
  99424. },
  99425. set: function (value) {
  99426. this._renderTargetTexture.refreshRate = value;
  99427. },
  99428. enumerable: true,
  99429. configurable: true
  99430. });
  99431. ReflectionProbe.prototype.getScene = function () {
  99432. return this._scene;
  99433. };
  99434. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99435. get: function () {
  99436. return this._renderTargetTexture;
  99437. },
  99438. enumerable: true,
  99439. configurable: true
  99440. });
  99441. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99442. get: function () {
  99443. return this._renderTargetTexture.renderList;
  99444. },
  99445. enumerable: true,
  99446. configurable: true
  99447. });
  99448. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99449. this._attachedMesh = mesh;
  99450. };
  99451. /**
  99452. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99453. *
  99454. * @param renderingGroupId The rendering group id corresponding to its index
  99455. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99456. */
  99457. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99458. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99459. };
  99460. ReflectionProbe.prototype.dispose = function () {
  99461. var index = this._scene.reflectionProbes.indexOf(this);
  99462. if (index !== -1) {
  99463. // Remove from the scene if found
  99464. this._scene.reflectionProbes.splice(index, 1);
  99465. }
  99466. if (this._renderTargetTexture) {
  99467. this._renderTargetTexture.dispose();
  99468. this._renderTargetTexture = null;
  99469. }
  99470. };
  99471. return ReflectionProbe;
  99472. }());
  99473. BABYLON.ReflectionProbe = ReflectionProbe;
  99474. })(BABYLON || (BABYLON = {}));
  99475. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99476. var BABYLON;
  99477. (function (BABYLON) {
  99478. /**
  99479. * Defines the layer scene component responsible to manage any layers
  99480. * in a given scene.
  99481. */
  99482. var LayerSceneComponent = /** @class */ (function () {
  99483. /**
  99484. * Creates a new instance of the component for the given scene
  99485. * @param scene Defines the scene to register the component in
  99486. */
  99487. function LayerSceneComponent(scene) {
  99488. /**
  99489. * The component name helpfull to identify the component in the list of scene components.
  99490. */
  99491. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99492. this.scene = scene;
  99493. this._engine = scene.getEngine();
  99494. scene.layers = new Array();
  99495. }
  99496. /**
  99497. * Registers the component in a given scene
  99498. */
  99499. LayerSceneComponent.prototype.register = function () {
  99500. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99501. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99502. };
  99503. /**
  99504. * Rebuilds the elements related to this component in case of
  99505. * context lost for instance.
  99506. */
  99507. LayerSceneComponent.prototype.rebuild = function () {
  99508. var layers = this.scene.layers;
  99509. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99510. var layer = layers_1[_i];
  99511. layer._rebuild();
  99512. }
  99513. };
  99514. /**
  99515. * Disposes the component and the associated ressources.
  99516. */
  99517. LayerSceneComponent.prototype.dispose = function () {
  99518. var layers = this.scene.layers;
  99519. while (layers.length) {
  99520. layers[0].dispose();
  99521. }
  99522. };
  99523. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99524. var layers = this.scene.layers;
  99525. if (layers.length) {
  99526. this._engine.setDepthBuffer(false);
  99527. var cameraLayerMask = camera.layerMask;
  99528. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99529. var layer = layers_2[_i];
  99530. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99531. layer.render();
  99532. }
  99533. }
  99534. this._engine.setDepthBuffer(true);
  99535. }
  99536. };
  99537. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99538. this._draw(camera, true);
  99539. };
  99540. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99541. this._draw(camera, false);
  99542. };
  99543. return LayerSceneComponent;
  99544. }());
  99545. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99546. })(BABYLON || (BABYLON = {}));
  99547. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99548. var BABYLON;
  99549. (function (BABYLON) {
  99550. var Layer = /** @class */ (function () {
  99551. function Layer(name, imgUrl, scene, isBackground, color) {
  99552. this.name = name;
  99553. this.scale = new BABYLON.Vector2(1, 1);
  99554. this.offset = new BABYLON.Vector2(0, 0);
  99555. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99556. this.layerMask = 0x0FFFFFFF;
  99557. this._vertexBuffers = {};
  99558. // Events
  99559. /**
  99560. * An event triggered when the layer is disposed.
  99561. */
  99562. this.onDisposeObservable = new BABYLON.Observable();
  99563. /**
  99564. * An event triggered before rendering the scene
  99565. */
  99566. this.onBeforeRenderObservable = new BABYLON.Observable();
  99567. /**
  99568. * An event triggered after rendering the scene
  99569. */
  99570. this.onAfterRenderObservable = new BABYLON.Observable();
  99571. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99572. this.isBackground = isBackground === undefined ? true : isBackground;
  99573. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99574. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99575. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99576. if (!layerComponent) {
  99577. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99578. this._scene._addComponent(layerComponent);
  99579. }
  99580. this._scene.layers.push(this);
  99581. var engine = this._scene.getEngine();
  99582. // VBO
  99583. var vertices = [];
  99584. vertices.push(1, 1);
  99585. vertices.push(-1, 1);
  99586. vertices.push(-1, -1);
  99587. vertices.push(1, -1);
  99588. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99589. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99590. this._createIndexBuffer();
  99591. // Effects
  99592. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99593. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99594. }
  99595. Object.defineProperty(Layer.prototype, "onDispose", {
  99596. set: function (callback) {
  99597. if (this._onDisposeObserver) {
  99598. this.onDisposeObservable.remove(this._onDisposeObserver);
  99599. }
  99600. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99601. },
  99602. enumerable: true,
  99603. configurable: true
  99604. });
  99605. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99606. set: function (callback) {
  99607. if (this._onBeforeRenderObserver) {
  99608. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99609. }
  99610. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99611. },
  99612. enumerable: true,
  99613. configurable: true
  99614. });
  99615. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99616. set: function (callback) {
  99617. if (this._onAfterRenderObserver) {
  99618. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99619. }
  99620. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99621. },
  99622. enumerable: true,
  99623. configurable: true
  99624. });
  99625. Layer.prototype._createIndexBuffer = function () {
  99626. var engine = this._scene.getEngine();
  99627. // Indices
  99628. var indices = [];
  99629. indices.push(0);
  99630. indices.push(1);
  99631. indices.push(2);
  99632. indices.push(0);
  99633. indices.push(2);
  99634. indices.push(3);
  99635. this._indexBuffer = engine.createIndexBuffer(indices);
  99636. };
  99637. Layer.prototype._rebuild = function () {
  99638. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99639. if (vb) {
  99640. vb._rebuild();
  99641. }
  99642. this._createIndexBuffer();
  99643. };
  99644. Layer.prototype.render = function () {
  99645. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99646. // Check
  99647. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99648. return;
  99649. var engine = this._scene.getEngine();
  99650. this.onBeforeRenderObservable.notifyObservers(this);
  99651. // Render
  99652. engine.enableEffect(currentEffect);
  99653. engine.setState(false);
  99654. // Texture
  99655. currentEffect.setTexture("textureSampler", this.texture);
  99656. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99657. // Color
  99658. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99659. // Scale / offset
  99660. currentEffect.setVector2("offset", this.offset);
  99661. currentEffect.setVector2("scale", this.scale);
  99662. // VBOs
  99663. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99664. // Draw order
  99665. if (!this.alphaTest) {
  99666. engine.setAlphaMode(this.alphaBlendingMode);
  99667. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99668. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99669. }
  99670. else {
  99671. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99672. }
  99673. this.onAfterRenderObservable.notifyObservers(this);
  99674. };
  99675. Layer.prototype.dispose = function () {
  99676. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99677. if (vertexBuffer) {
  99678. vertexBuffer.dispose();
  99679. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99680. }
  99681. if (this._indexBuffer) {
  99682. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99683. this._indexBuffer = null;
  99684. }
  99685. if (this.texture) {
  99686. this.texture.dispose();
  99687. this.texture = null;
  99688. }
  99689. // Remove from scene
  99690. var index = this._scene.layers.indexOf(this);
  99691. this._scene.layers.splice(index, 1);
  99692. // Callback
  99693. this.onDisposeObservable.notifyObservers(this);
  99694. this.onDisposeObservable.clear();
  99695. this.onAfterRenderObservable.clear();
  99696. this.onBeforeRenderObservable.clear();
  99697. };
  99698. return Layer;
  99699. }());
  99700. BABYLON.Layer = Layer;
  99701. })(BABYLON || (BABYLON = {}));
  99702. //# sourceMappingURL=babylon.layer.js.map
  99703. var BABYLON;
  99704. (function (BABYLON) {
  99705. var TextureTools = /** @class */ (function () {
  99706. function TextureTools() {
  99707. }
  99708. /**
  99709. * Uses the GPU to create a copy texture rescaled at a given size
  99710. * @param texture Texture to copy from
  99711. * @param width Desired width
  99712. * @param height Desired height
  99713. * @return Generated texture
  99714. */
  99715. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99716. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99717. var scene = texture.getScene();
  99718. var engine = scene.getEngine();
  99719. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99720. rtt.wrapU = texture.wrapU;
  99721. rtt.wrapV = texture.wrapV;
  99722. rtt.uOffset = texture.uOffset;
  99723. rtt.vOffset = texture.vOffset;
  99724. rtt.uScale = texture.uScale;
  99725. rtt.vScale = texture.vScale;
  99726. rtt.uAng = texture.uAng;
  99727. rtt.vAng = texture.vAng;
  99728. rtt.wAng = texture.wAng;
  99729. rtt.coordinatesIndex = texture.coordinatesIndex;
  99730. rtt.level = texture.level;
  99731. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99732. rtt._texture.isReady = false;
  99733. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99734. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99735. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99736. passPostProcess.getEffect().executeWhenCompiled(function () {
  99737. passPostProcess.onApply = function (effect) {
  99738. effect.setTexture("textureSampler", texture);
  99739. };
  99740. var internalTexture = rtt.getInternalTexture();
  99741. if (internalTexture) {
  99742. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99743. engine.unBindFramebuffer(internalTexture);
  99744. rtt.disposeFramebufferObjects();
  99745. passPostProcess.dispose();
  99746. internalTexture.isReady = true;
  99747. }
  99748. });
  99749. return rtt;
  99750. };
  99751. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99752. if (!scene._environmentBRDFTexture) {
  99753. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99754. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99755. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99756. scene._environmentBRDFTexture = texture;
  99757. }
  99758. return scene._environmentBRDFTexture;
  99759. };
  99760. 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=";
  99761. return TextureTools;
  99762. }());
  99763. BABYLON.TextureTools = TextureTools;
  99764. })(BABYLON || (BABYLON = {}));
  99765. //# sourceMappingURL=babylon.textureTools.js.map
  99766. var BABYLON;
  99767. (function (BABYLON) {
  99768. var FramingBehavior = /** @class */ (function () {
  99769. function FramingBehavior() {
  99770. this._mode = FramingBehavior.FitFrustumSidesMode;
  99771. this._radiusScale = 1.0;
  99772. this._positionScale = 0.5;
  99773. this._defaultElevation = 0.3;
  99774. this._elevationReturnTime = 1500;
  99775. this._elevationReturnWaitTime = 1000;
  99776. this._zoomStopsAnimation = false;
  99777. this._framingTime = 1500;
  99778. this._isPointerDown = false;
  99779. this._lastInteractionTime = -Infinity;
  99780. // Framing control
  99781. this._animatables = new Array();
  99782. this._betaIsAnimating = false;
  99783. }
  99784. Object.defineProperty(FramingBehavior.prototype, "name", {
  99785. get: function () {
  99786. return "Framing";
  99787. },
  99788. enumerable: true,
  99789. configurable: true
  99790. });
  99791. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99792. /**
  99793. * Gets current mode used by the behavior.
  99794. */
  99795. get: function () {
  99796. return this._mode;
  99797. },
  99798. /**
  99799. * Sets the current mode used by the behavior
  99800. */
  99801. set: function (mode) {
  99802. this._mode = mode;
  99803. },
  99804. enumerable: true,
  99805. configurable: true
  99806. });
  99807. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99808. /**
  99809. * Gets the scale applied to the radius
  99810. */
  99811. get: function () {
  99812. return this._radiusScale;
  99813. },
  99814. /**
  99815. * Sets the scale applied to the radius (1 by default)
  99816. */
  99817. set: function (radius) {
  99818. this._radiusScale = radius;
  99819. },
  99820. enumerable: true,
  99821. configurable: true
  99822. });
  99823. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99824. /**
  99825. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99826. */
  99827. get: function () {
  99828. return this._positionScale;
  99829. },
  99830. /**
  99831. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99832. */
  99833. set: function (scale) {
  99834. this._positionScale = scale;
  99835. },
  99836. enumerable: true,
  99837. configurable: true
  99838. });
  99839. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99840. /**
  99841. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99842. * behaviour is triggered, in radians.
  99843. */
  99844. get: function () {
  99845. return this._defaultElevation;
  99846. },
  99847. /**
  99848. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99849. * behaviour is triggered, in radians.
  99850. */
  99851. set: function (elevation) {
  99852. this._defaultElevation = elevation;
  99853. },
  99854. enumerable: true,
  99855. configurable: true
  99856. });
  99857. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99858. /**
  99859. * Gets the time (in milliseconds) taken to return to the default beta position.
  99860. * Negative value indicates camera should not return to default.
  99861. */
  99862. get: function () {
  99863. return this._elevationReturnTime;
  99864. },
  99865. /**
  99866. * Sets the time (in milliseconds) taken to return to the default beta position.
  99867. * Negative value indicates camera should not return to default.
  99868. */
  99869. set: function (speed) {
  99870. this._elevationReturnTime = speed;
  99871. },
  99872. enumerable: true,
  99873. configurable: true
  99874. });
  99875. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99876. /**
  99877. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99878. */
  99879. get: function () {
  99880. return this._elevationReturnWaitTime;
  99881. },
  99882. /**
  99883. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99884. */
  99885. set: function (time) {
  99886. this._elevationReturnWaitTime = time;
  99887. },
  99888. enumerable: true,
  99889. configurable: true
  99890. });
  99891. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99892. /**
  99893. * Gets the flag that indicates if user zooming should stop animation.
  99894. */
  99895. get: function () {
  99896. return this._zoomStopsAnimation;
  99897. },
  99898. /**
  99899. * Sets the flag that indicates if user zooming should stop animation.
  99900. */
  99901. set: function (flag) {
  99902. this._zoomStopsAnimation = flag;
  99903. },
  99904. enumerable: true,
  99905. configurable: true
  99906. });
  99907. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99908. /**
  99909. * Gets the transition time when framing the mesh, in milliseconds
  99910. */
  99911. get: function () {
  99912. return this._framingTime;
  99913. },
  99914. /**
  99915. * Sets the transition time when framing the mesh, in milliseconds
  99916. */
  99917. set: function (time) {
  99918. this._framingTime = time;
  99919. },
  99920. enumerable: true,
  99921. configurable: true
  99922. });
  99923. FramingBehavior.prototype.init = function () {
  99924. // Do notihng
  99925. };
  99926. FramingBehavior.prototype.attach = function (camera) {
  99927. var _this = this;
  99928. this._attachedCamera = camera;
  99929. var scene = this._attachedCamera.getScene();
  99930. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99931. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99932. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99933. _this._isPointerDown = true;
  99934. return;
  99935. }
  99936. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99937. _this._isPointerDown = false;
  99938. }
  99939. });
  99940. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99941. if (mesh) {
  99942. _this.zoomOnMesh(mesh);
  99943. }
  99944. });
  99945. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99946. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99947. _this._applyUserInteraction();
  99948. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99949. // back to the default position after a given timeout
  99950. _this._maintainCameraAboveGround();
  99951. });
  99952. };
  99953. FramingBehavior.prototype.detach = function () {
  99954. if (!this._attachedCamera) {
  99955. return;
  99956. }
  99957. var scene = this._attachedCamera.getScene();
  99958. if (this._onPrePointerObservableObserver) {
  99959. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99960. }
  99961. if (this._onAfterCheckInputsObserver) {
  99962. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99963. }
  99964. if (this._onMeshTargetChangedObserver) {
  99965. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99966. }
  99967. this._attachedCamera = null;
  99968. };
  99969. /**
  99970. * Targets the given mesh and updates zoom level accordingly.
  99971. * @param mesh The mesh to target.
  99972. * @param radius Optional. If a cached radius position already exists, overrides default.
  99973. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99974. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99975. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99976. */
  99977. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99978. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99979. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99980. mesh.computeWorldMatrix(true);
  99981. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99982. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99983. };
  99984. /**
  99985. * Targets the given mesh with its children and updates zoom level accordingly.
  99986. * @param mesh The mesh to target.
  99987. * @param radius Optional. If a cached radius position already exists, overrides default.
  99988. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99989. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99990. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99991. */
  99992. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99993. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99994. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99995. mesh.computeWorldMatrix(true);
  99996. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99997. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99998. };
  99999. /**
  100000. * Targets the given meshes with their children and updates zoom level accordingly.
  100001. * @param meshes The mesh to target.
  100002. * @param radius Optional. If a cached radius position already exists, overrides default.
  100003. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100004. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100005. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100006. */
  100007. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  100008. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100009. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100010. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  100011. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  100012. for (var i = 0; i < meshes.length; i++) {
  100013. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  100014. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  100015. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  100016. }
  100017. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  100018. };
  100019. /**
  100020. * Targets the given mesh and updates zoom level accordingly.
  100021. * @param mesh The mesh to target.
  100022. * @param radius Optional. If a cached radius position already exists, overrides default.
  100023. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100024. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100025. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100026. */
  100027. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  100028. var _this = this;
  100029. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100030. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100031. var zoomTarget;
  100032. if (!this._attachedCamera) {
  100033. return;
  100034. }
  100035. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  100036. var bottom = minimumWorld.y;
  100037. var top = maximumWorld.y;
  100038. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  100039. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  100040. if (focusOnOriginXZ) {
  100041. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  100042. }
  100043. else {
  100044. var centerWorld = minimumWorld.add(radiusWorld);
  100045. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  100046. }
  100047. if (!this._vectorTransition) {
  100048. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  100049. }
  100050. this._betaIsAnimating = true;
  100051. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  100052. if (animatable) {
  100053. this._animatables.push(animatable);
  100054. }
  100055. // sets the radius and lower radius bounds
  100056. // Small delta ensures camera is not always at lower zoom limit.
  100057. var radius = 0;
  100058. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  100059. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100060. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  100061. radius = position;
  100062. }
  100063. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100064. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100065. if (this._attachedCamera.lowerRadiusLimit === null) {
  100066. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  100067. }
  100068. }
  100069. // Set sensibilities
  100070. var extend = maximumWorld.subtract(minimumWorld).length();
  100071. this._attachedCamera.panningSensibility = 5000 / extend;
  100072. this._attachedCamera.wheelPrecision = 100 / radius;
  100073. // transition to new radius
  100074. if (!this._radiusTransition) {
  100075. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100076. }
  100077. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  100078. _this.stopAllAnimations();
  100079. if (onAnimationEnd) {
  100080. onAnimationEnd();
  100081. }
  100082. if (_this._attachedCamera) {
  100083. _this._attachedCamera.storeState();
  100084. }
  100085. });
  100086. if (animatable) {
  100087. this._animatables.push(animatable);
  100088. }
  100089. };
  100090. /**
  100091. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  100092. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  100093. * frustum width.
  100094. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  100095. * to fully enclose the mesh in the viewing frustum.
  100096. */
  100097. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  100098. var size = maximumWorld.subtract(minimumWorld);
  100099. var boxVectorGlobalDiagonal = size.length();
  100100. var frustumSlope = this._getFrustumSlope();
  100101. // Formula for setting distance
  100102. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  100103. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  100104. // Horizon distance
  100105. var radius = radiusWithoutFraming * this._radiusScale;
  100106. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  100107. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  100108. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  100109. var camera = this._attachedCamera;
  100110. if (!camera) {
  100111. return 0;
  100112. }
  100113. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100114. // Don't exceed the requested limit
  100115. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  100116. }
  100117. // Don't exceed the upper radius limit
  100118. if (camera.upperRadiusLimit) {
  100119. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  100120. }
  100121. return distance;
  100122. };
  100123. /**
  100124. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  100125. * is automatically returned to its default position (expected to be above ground plane).
  100126. */
  100127. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  100128. var _this = this;
  100129. if (this._elevationReturnTime < 0) {
  100130. return;
  100131. }
  100132. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  100133. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  100134. var limitBeta = Math.PI * 0.5;
  100135. // Bring the camera back up if below the ground plane
  100136. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  100137. this._betaIsAnimating = true;
  100138. //Transition to new position
  100139. this.stopAllAnimations();
  100140. if (!this._betaTransition) {
  100141. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100142. }
  100143. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  100144. _this._clearAnimationLocks();
  100145. _this.stopAllAnimations();
  100146. });
  100147. if (animatabe) {
  100148. this._animatables.push(animatabe);
  100149. }
  100150. }
  100151. };
  100152. /**
  100153. * Returns the frustum slope based on the canvas ratio and camera FOV
  100154. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  100155. */
  100156. FramingBehavior.prototype._getFrustumSlope = function () {
  100157. // Calculate the viewport ratio
  100158. // Aspect Ratio is Height/Width.
  100159. var camera = this._attachedCamera;
  100160. if (!camera) {
  100161. return BABYLON.Vector2.Zero();
  100162. }
  100163. var engine = camera.getScene().getEngine();
  100164. var aspectRatio = engine.getAspectRatio(camera);
  100165. // Camera FOV is the vertical field of view (top-bottom) in radians.
  100166. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  100167. var frustumSlopeY = Math.tan(camera.fov / 2);
  100168. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  100169. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  100170. // along the forward vector.
  100171. var frustumSlopeX = frustumSlopeY * aspectRatio;
  100172. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  100173. };
  100174. /**
  100175. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  100176. */
  100177. FramingBehavior.prototype._clearAnimationLocks = function () {
  100178. this._betaIsAnimating = false;
  100179. };
  100180. /**
  100181. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100182. */
  100183. FramingBehavior.prototype._applyUserInteraction = function () {
  100184. if (this.isUserIsMoving) {
  100185. this._lastInteractionTime = BABYLON.Tools.Now;
  100186. this.stopAllAnimations();
  100187. this._clearAnimationLocks();
  100188. }
  100189. };
  100190. /**
  100191. * Stops and removes all animations that have been applied to the camera
  100192. */
  100193. FramingBehavior.prototype.stopAllAnimations = function () {
  100194. if (this._attachedCamera) {
  100195. this._attachedCamera.animations = [];
  100196. }
  100197. while (this._animatables.length) {
  100198. if (this._animatables[0]) {
  100199. this._animatables[0].onAnimationEnd = null;
  100200. this._animatables[0].stop();
  100201. }
  100202. this._animatables.shift();
  100203. }
  100204. };
  100205. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100206. /**
  100207. * Gets a value indicating if the user is moving the camera
  100208. */
  100209. get: function () {
  100210. if (!this._attachedCamera) {
  100211. return false;
  100212. }
  100213. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100214. this._attachedCamera.inertialBetaOffset !== 0 ||
  100215. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100216. this._attachedCamera.inertialPanningX !== 0 ||
  100217. this._attachedCamera.inertialPanningY !== 0 ||
  100218. this._isPointerDown;
  100219. },
  100220. enumerable: true,
  100221. configurable: true
  100222. });
  100223. /**
  100224. * The easing function used by animations
  100225. */
  100226. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100227. /**
  100228. * The easing mode used by animations
  100229. */
  100230. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100231. // Statics
  100232. /**
  100233. * The camera can move all the way towards the mesh.
  100234. */
  100235. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100236. /**
  100237. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100238. */
  100239. FramingBehavior.FitFrustumSidesMode = 1;
  100240. return FramingBehavior;
  100241. }());
  100242. BABYLON.FramingBehavior = FramingBehavior;
  100243. })(BABYLON || (BABYLON = {}));
  100244. //# sourceMappingURL=babylon.framingBehavior.js.map
  100245. var BABYLON;
  100246. (function (BABYLON) {
  100247. /**
  100248. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100249. */
  100250. var BouncingBehavior = /** @class */ (function () {
  100251. function BouncingBehavior() {
  100252. /**
  100253. * The duration of the animation, in milliseconds
  100254. */
  100255. this.transitionDuration = 450;
  100256. /**
  100257. * Length of the distance animated by the transition when lower radius is reached
  100258. */
  100259. this.lowerRadiusTransitionRange = 2;
  100260. /**
  100261. * Length of the distance animated by the transition when upper radius is reached
  100262. */
  100263. this.upperRadiusTransitionRange = -2;
  100264. this._autoTransitionRange = false;
  100265. // Animations
  100266. this._radiusIsAnimating = false;
  100267. this._radiusBounceTransition = null;
  100268. this._animatables = new Array();
  100269. }
  100270. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100271. get: function () {
  100272. return "Bouncing";
  100273. },
  100274. enumerable: true,
  100275. configurable: true
  100276. });
  100277. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100278. /**
  100279. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100280. */
  100281. get: function () {
  100282. return this._autoTransitionRange;
  100283. },
  100284. /**
  100285. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100286. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100287. */
  100288. set: function (value) {
  100289. var _this = this;
  100290. if (this._autoTransitionRange === value) {
  100291. return;
  100292. }
  100293. this._autoTransitionRange = value;
  100294. var camera = this._attachedCamera;
  100295. if (!camera) {
  100296. return;
  100297. }
  100298. if (value) {
  100299. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100300. if (!mesh) {
  100301. return;
  100302. }
  100303. mesh.computeWorldMatrix(true);
  100304. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100305. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100306. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100307. });
  100308. }
  100309. else if (this._onMeshTargetChangedObserver) {
  100310. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100311. }
  100312. },
  100313. enumerable: true,
  100314. configurable: true
  100315. });
  100316. BouncingBehavior.prototype.init = function () {
  100317. // Do notihng
  100318. };
  100319. BouncingBehavior.prototype.attach = function (camera) {
  100320. var _this = this;
  100321. this._attachedCamera = camera;
  100322. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100323. if (!_this._attachedCamera) {
  100324. return;
  100325. }
  100326. // Add the bounce animation to the lower radius limit
  100327. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100328. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100329. }
  100330. // Add the bounce animation to the upper radius limit
  100331. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100332. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100333. }
  100334. });
  100335. };
  100336. BouncingBehavior.prototype.detach = function () {
  100337. if (!this._attachedCamera) {
  100338. return;
  100339. }
  100340. if (this._onAfterCheckInputsObserver) {
  100341. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100342. }
  100343. if (this._onMeshTargetChangedObserver) {
  100344. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100345. }
  100346. this._attachedCamera = null;
  100347. };
  100348. /**
  100349. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100350. * @param radiusLimit The limit to check against.
  100351. * @return Bool to indicate if at limit.
  100352. */
  100353. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100354. if (!this._attachedCamera) {
  100355. return false;
  100356. }
  100357. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100358. return true;
  100359. }
  100360. return false;
  100361. };
  100362. /**
  100363. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100364. * @param radiusDelta The delta by which to animate to. Can be negative.
  100365. */
  100366. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100367. var _this = this;
  100368. if (!this._attachedCamera) {
  100369. return;
  100370. }
  100371. if (!this._radiusBounceTransition) {
  100372. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100373. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100374. }
  100375. // Prevent zoom until bounce has completed
  100376. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100377. this._attachedCamera.wheelPrecision = Infinity;
  100378. this._attachedCamera.inertialRadiusOffset = 0;
  100379. // Animate to the radius limit
  100380. this.stopAllAnimations();
  100381. this._radiusIsAnimating = true;
  100382. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100383. if (animatable) {
  100384. this._animatables.push(animatable);
  100385. }
  100386. };
  100387. /**
  100388. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100389. */
  100390. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100391. this._radiusIsAnimating = false;
  100392. if (this._attachedCamera) {
  100393. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100394. }
  100395. };
  100396. /**
  100397. * Stops and removes all animations that have been applied to the camera
  100398. */
  100399. BouncingBehavior.prototype.stopAllAnimations = function () {
  100400. if (this._attachedCamera) {
  100401. this._attachedCamera.animations = [];
  100402. }
  100403. while (this._animatables.length) {
  100404. this._animatables[0].onAnimationEnd = null;
  100405. this._animatables[0].stop();
  100406. this._animatables.shift();
  100407. }
  100408. };
  100409. /**
  100410. * The easing function used by animations
  100411. */
  100412. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100413. /**
  100414. * The easing mode used by animations
  100415. */
  100416. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100417. return BouncingBehavior;
  100418. }());
  100419. BABYLON.BouncingBehavior = BouncingBehavior;
  100420. })(BABYLON || (BABYLON = {}));
  100421. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100422. var BABYLON;
  100423. (function (BABYLON) {
  100424. var AutoRotationBehavior = /** @class */ (function () {
  100425. function AutoRotationBehavior() {
  100426. this._zoomStopsAnimation = false;
  100427. this._idleRotationSpeed = 0.05;
  100428. this._idleRotationWaitTime = 2000;
  100429. this._idleRotationSpinupTime = 2000;
  100430. this._isPointerDown = false;
  100431. this._lastFrameTime = null;
  100432. this._lastInteractionTime = -Infinity;
  100433. this._cameraRotationSpeed = 0;
  100434. this._lastFrameRadius = 0;
  100435. }
  100436. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100437. get: function () {
  100438. return "AutoRotation";
  100439. },
  100440. enumerable: true,
  100441. configurable: true
  100442. });
  100443. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100444. /**
  100445. * Gets the flag that indicates if user zooming should stop animation.
  100446. */
  100447. get: function () {
  100448. return this._zoomStopsAnimation;
  100449. },
  100450. /**
  100451. * Sets the flag that indicates if user zooming should stop animation.
  100452. */
  100453. set: function (flag) {
  100454. this._zoomStopsAnimation = flag;
  100455. },
  100456. enumerable: true,
  100457. configurable: true
  100458. });
  100459. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100460. /**
  100461. * Gets the default speed at which the camera rotates around the model.
  100462. */
  100463. get: function () {
  100464. return this._idleRotationSpeed;
  100465. },
  100466. /**
  100467. * Sets the default speed at which the camera rotates around the model.
  100468. */
  100469. set: function (speed) {
  100470. this._idleRotationSpeed = speed;
  100471. },
  100472. enumerable: true,
  100473. configurable: true
  100474. });
  100475. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100476. /**
  100477. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100478. */
  100479. get: function () {
  100480. return this._idleRotationWaitTime;
  100481. },
  100482. /**
  100483. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100484. */
  100485. set: function (time) {
  100486. this._idleRotationWaitTime = time;
  100487. },
  100488. enumerable: true,
  100489. configurable: true
  100490. });
  100491. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100492. /**
  100493. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100494. */
  100495. get: function () {
  100496. return this._idleRotationSpinupTime;
  100497. },
  100498. /**
  100499. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100500. */
  100501. set: function (time) {
  100502. this._idleRotationSpinupTime = time;
  100503. },
  100504. enumerable: true,
  100505. configurable: true
  100506. });
  100507. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100508. /**
  100509. * Gets a value indicating if the camera is currently rotating because of this behavior
  100510. */
  100511. get: function () {
  100512. return Math.abs(this._cameraRotationSpeed) > 0;
  100513. },
  100514. enumerable: true,
  100515. configurable: true
  100516. });
  100517. AutoRotationBehavior.prototype.init = function () {
  100518. // Do notihng
  100519. };
  100520. AutoRotationBehavior.prototype.attach = function (camera) {
  100521. var _this = this;
  100522. this._attachedCamera = camera;
  100523. var scene = this._attachedCamera.getScene();
  100524. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100525. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100526. _this._isPointerDown = true;
  100527. return;
  100528. }
  100529. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100530. _this._isPointerDown = false;
  100531. }
  100532. });
  100533. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100534. var now = BABYLON.Tools.Now;
  100535. var dt = 0;
  100536. if (_this._lastFrameTime != null) {
  100537. dt = now - _this._lastFrameTime;
  100538. }
  100539. _this._lastFrameTime = now;
  100540. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100541. _this._applyUserInteraction();
  100542. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100543. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100544. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100545. // Step camera rotation by rotation speed
  100546. if (_this._attachedCamera) {
  100547. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100548. }
  100549. });
  100550. };
  100551. AutoRotationBehavior.prototype.detach = function () {
  100552. if (!this._attachedCamera) {
  100553. return;
  100554. }
  100555. var scene = this._attachedCamera.getScene();
  100556. if (this._onPrePointerObservableObserver) {
  100557. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100558. }
  100559. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100560. this._attachedCamera = null;
  100561. };
  100562. /**
  100563. * Returns true if user is scrolling.
  100564. * @return true if user is scrolling.
  100565. */
  100566. AutoRotationBehavior.prototype._userIsZooming = function () {
  100567. if (!this._attachedCamera) {
  100568. return false;
  100569. }
  100570. return this._attachedCamera.inertialRadiusOffset !== 0;
  100571. };
  100572. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100573. if (!this._attachedCamera) {
  100574. return false;
  100575. }
  100576. var zoomHasHitLimit = false;
  100577. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100578. zoomHasHitLimit = true;
  100579. }
  100580. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100581. this._lastFrameRadius = this._attachedCamera.radius;
  100582. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100583. };
  100584. /**
  100585. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100586. */
  100587. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100588. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100589. this._lastInteractionTime = BABYLON.Tools.Now;
  100590. }
  100591. };
  100592. // Tools
  100593. AutoRotationBehavior.prototype._userIsMoving = function () {
  100594. if (!this._attachedCamera) {
  100595. return false;
  100596. }
  100597. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100598. this._attachedCamera.inertialBetaOffset !== 0 ||
  100599. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100600. this._attachedCamera.inertialPanningX !== 0 ||
  100601. this._attachedCamera.inertialPanningY !== 0 ||
  100602. this._isPointerDown;
  100603. };
  100604. return AutoRotationBehavior;
  100605. }());
  100606. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100607. })(BABYLON || (BABYLON = {}));
  100608. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100609. var BABYLON;
  100610. (function (BABYLON) {
  100611. var NullEngineOptions = /** @class */ (function () {
  100612. function NullEngineOptions() {
  100613. this.renderWidth = 512;
  100614. this.renderHeight = 256;
  100615. this.textureSize = 512;
  100616. this.deterministicLockstep = false;
  100617. this.lockstepMaxSteps = 4;
  100618. }
  100619. return NullEngineOptions;
  100620. }());
  100621. BABYLON.NullEngineOptions = NullEngineOptions;
  100622. /**
  100623. * The null engine class provides support for headless version of babylon.js.
  100624. * This can be used in server side scenario or for testing purposes
  100625. */
  100626. var NullEngine = /** @class */ (function (_super) {
  100627. __extends(NullEngine, _super);
  100628. function NullEngine(options) {
  100629. if (options === void 0) { options = new NullEngineOptions(); }
  100630. var _this = _super.call(this, null) || this;
  100631. if (options.deterministicLockstep === undefined) {
  100632. options.deterministicLockstep = false;
  100633. }
  100634. if (options.lockstepMaxSteps === undefined) {
  100635. options.lockstepMaxSteps = 4;
  100636. }
  100637. _this._options = options;
  100638. // Init caps
  100639. // We consider we are on a webgl1 capable device
  100640. _this._caps = new BABYLON.EngineCapabilities();
  100641. _this._caps.maxTexturesImageUnits = 16;
  100642. _this._caps.maxVertexTextureImageUnits = 16;
  100643. _this._caps.maxTextureSize = 512;
  100644. _this._caps.maxCubemapTextureSize = 512;
  100645. _this._caps.maxRenderTextureSize = 512;
  100646. _this._caps.maxVertexAttribs = 16;
  100647. _this._caps.maxVaryingVectors = 16;
  100648. _this._caps.maxFragmentUniformVectors = 16;
  100649. _this._caps.maxVertexUniformVectors = 16;
  100650. // Extensions
  100651. _this._caps.standardDerivatives = false;
  100652. _this._caps.astc = null;
  100653. _this._caps.s3tc = null;
  100654. _this._caps.pvrtc = null;
  100655. _this._caps.etc1 = null;
  100656. _this._caps.etc2 = null;
  100657. _this._caps.textureAnisotropicFilterExtension = null;
  100658. _this._caps.maxAnisotropy = 0;
  100659. _this._caps.uintIndices = false;
  100660. _this._caps.fragmentDepthSupported = false;
  100661. _this._caps.highPrecisionShaderSupported = true;
  100662. _this._caps.colorBufferFloat = false;
  100663. _this._caps.textureFloat = false;
  100664. _this._caps.textureFloatLinearFiltering = false;
  100665. _this._caps.textureFloatRender = false;
  100666. _this._caps.textureHalfFloat = false;
  100667. _this._caps.textureHalfFloatLinearFiltering = false;
  100668. _this._caps.textureHalfFloatRender = false;
  100669. _this._caps.textureLOD = false;
  100670. _this._caps.drawBuffersExtension = false;
  100671. _this._caps.depthTextureExtension = false;
  100672. _this._caps.vertexArrayObject = false;
  100673. _this._caps.instancedArrays = false;
  100674. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100675. // Wrappers
  100676. if (typeof URL === "undefined") {
  100677. URL = {
  100678. createObjectURL: function () { },
  100679. revokeObjectURL: function () { }
  100680. };
  100681. }
  100682. if (typeof Blob === "undefined") {
  100683. Blob = function () { };
  100684. }
  100685. return _this;
  100686. }
  100687. NullEngine.prototype.isDeterministicLockStep = function () {
  100688. return this._options.deterministicLockstep;
  100689. };
  100690. NullEngine.prototype.getLockstepMaxSteps = function () {
  100691. return this._options.lockstepMaxSteps;
  100692. };
  100693. NullEngine.prototype.getHardwareScalingLevel = function () {
  100694. return 1.0;
  100695. };
  100696. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100697. return {
  100698. capacity: 0,
  100699. references: 1,
  100700. is32Bits: false
  100701. };
  100702. };
  100703. NullEngine.prototype.createIndexBuffer = function (indices) {
  100704. return {
  100705. capacity: 0,
  100706. references: 1,
  100707. is32Bits: false
  100708. };
  100709. };
  100710. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100711. if (stencil === void 0) { stencil = false; }
  100712. };
  100713. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100714. if (useScreen === void 0) { useScreen = false; }
  100715. if (!useScreen && this._currentRenderTarget) {
  100716. return this._currentRenderTarget.width;
  100717. }
  100718. return this._options.renderWidth;
  100719. };
  100720. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100721. if (useScreen === void 0) { useScreen = false; }
  100722. if (!useScreen && this._currentRenderTarget) {
  100723. return this._currentRenderTarget.height;
  100724. }
  100725. return this._options.renderHeight;
  100726. };
  100727. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100728. this._cachedViewport = viewport;
  100729. };
  100730. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100731. return {
  100732. transformFeedback: null,
  100733. __SPECTOR_rebuildProgram: null
  100734. };
  100735. };
  100736. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100737. return [];
  100738. };
  100739. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100740. return [];
  100741. };
  100742. NullEngine.prototype.bindSamplers = function (effect) {
  100743. this._currentEffect = null;
  100744. };
  100745. NullEngine.prototype.enableEffect = function (effect) {
  100746. this._currentEffect = effect;
  100747. if (effect.onBind) {
  100748. effect.onBind(effect);
  100749. }
  100750. effect.onBindObservable.notifyObservers(effect);
  100751. };
  100752. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100753. if (zOffset === void 0) { zOffset = 0; }
  100754. if (reverseSide === void 0) { reverseSide = false; }
  100755. };
  100756. NullEngine.prototype.setIntArray = function (uniform, array) {
  100757. };
  100758. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100759. };
  100760. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100761. };
  100762. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100763. };
  100764. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100765. };
  100766. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100767. };
  100768. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100769. };
  100770. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100771. };
  100772. NullEngine.prototype.setArray = function (uniform, array) {
  100773. };
  100774. NullEngine.prototype.setArray2 = function (uniform, array) {
  100775. };
  100776. NullEngine.prototype.setArray3 = function (uniform, array) {
  100777. };
  100778. NullEngine.prototype.setArray4 = function (uniform, array) {
  100779. };
  100780. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100781. };
  100782. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100783. };
  100784. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100785. };
  100786. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100787. };
  100788. NullEngine.prototype.setFloat = function (uniform, value) {
  100789. };
  100790. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100791. };
  100792. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100793. };
  100794. NullEngine.prototype.setBool = function (uniform, bool) {
  100795. };
  100796. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100797. };
  100798. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100799. };
  100800. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100801. };
  100802. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100803. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100804. if (this._alphaMode === mode) {
  100805. return;
  100806. }
  100807. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100808. if (!noDepthWriteChange) {
  100809. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100810. }
  100811. this._alphaMode = mode;
  100812. };
  100813. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100814. };
  100815. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100816. if (this.preventCacheWipeBetweenFrames) {
  100817. return;
  100818. }
  100819. this.resetTextureCache();
  100820. this._currentEffect = null;
  100821. if (bruteForce) {
  100822. this._currentProgram = null;
  100823. this._stencilState.reset();
  100824. this._depthCullingState.reset();
  100825. this._alphaState.reset();
  100826. }
  100827. this._cachedVertexBuffers = null;
  100828. this._cachedIndexBuffer = null;
  100829. this._cachedEffectForVertexBuffers = null;
  100830. };
  100831. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100832. };
  100833. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100834. };
  100835. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100836. };
  100837. NullEngine.prototype._createTexture = function () {
  100838. return {};
  100839. };
  100840. NullEngine.prototype._releaseTexture = function (texture) {
  100841. };
  100842. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100844. if (onLoad === void 0) { onLoad = null; }
  100845. if (onError === void 0) { onError = null; }
  100846. if (buffer === void 0) { buffer = null; }
  100847. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100848. var url = String(urlArg);
  100849. texture.url = url;
  100850. texture.generateMipMaps = !noMipmap;
  100851. texture.samplingMode = samplingMode;
  100852. texture.invertY = invertY;
  100853. texture.baseWidth = this._options.textureSize;
  100854. texture.baseHeight = this._options.textureSize;
  100855. texture.width = this._options.textureSize;
  100856. texture.height = this._options.textureSize;
  100857. if (format) {
  100858. texture.format = format;
  100859. }
  100860. texture.isReady = true;
  100861. if (onLoad) {
  100862. onLoad();
  100863. }
  100864. this._internalTexturesCache.push(texture);
  100865. return texture;
  100866. };
  100867. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100868. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100869. if (options !== undefined && typeof options === "object") {
  100870. fullOptions.generateMipMaps = options.generateMipMaps;
  100871. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100872. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100873. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100874. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100875. }
  100876. else {
  100877. fullOptions.generateMipMaps = options;
  100878. fullOptions.generateDepthBuffer = true;
  100879. fullOptions.generateStencilBuffer = false;
  100880. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100881. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100882. }
  100883. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100884. var width = size.width || size;
  100885. var height = size.height || size;
  100886. texture._depthStencilBuffer = {};
  100887. texture._framebuffer = {};
  100888. texture.baseWidth = width;
  100889. texture.baseHeight = height;
  100890. texture.width = width;
  100891. texture.height = height;
  100892. texture.isReady = true;
  100893. texture.samples = 1;
  100894. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100895. texture.samplingMode = fullOptions.samplingMode;
  100896. texture.type = fullOptions.type;
  100897. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100898. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100899. this._internalTexturesCache.push(texture);
  100900. return texture;
  100901. };
  100902. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100903. texture.samplingMode = samplingMode;
  100904. };
  100905. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100906. if (this._currentRenderTarget) {
  100907. this.unBindFramebuffer(this._currentRenderTarget);
  100908. }
  100909. this._currentRenderTarget = texture;
  100910. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100911. if (this._cachedViewport && !forceFullscreenViewport) {
  100912. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100913. }
  100914. };
  100915. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100916. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100917. this._currentRenderTarget = null;
  100918. if (onBeforeUnbind) {
  100919. if (texture._MSAAFramebuffer) {
  100920. this._currentFramebuffer = texture._framebuffer;
  100921. }
  100922. onBeforeUnbind();
  100923. }
  100924. this._currentFramebuffer = null;
  100925. };
  100926. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100927. var vbo = {
  100928. capacity: 1,
  100929. references: 1,
  100930. is32Bits: false
  100931. };
  100932. return vbo;
  100933. };
  100934. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100935. if (premulAlpha === void 0) { premulAlpha = false; }
  100936. };
  100937. /**
  100938. * Get the current error code of the webGL context
  100939. * @returns the error code
  100940. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  100941. */
  100942. NullEngine.prototype.getError = function () {
  100943. return 0;
  100944. };
  100945. /** @hidden */
  100946. NullEngine.prototype._getUnpackAlignement = function () {
  100947. return 1;
  100948. };
  100949. /** @hidden */
  100950. NullEngine.prototype._unpackFlipY = function (value) {
  100951. };
  100952. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100953. if (offset === void 0) { offset = 0; }
  100954. };
  100955. /**
  100956. * Updates a dynamic vertex buffer.
  100957. * @param vertexBuffer the vertex buffer to update
  100958. * @param data the data used to update the vertex buffer
  100959. * @param byteOffset the byte offset of the data (optional)
  100960. * @param byteLength the byte length of the data (optional)
  100961. */
  100962. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100963. };
  100964. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100965. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100966. this._boundTexturesCache[this._activeChannel] = texture;
  100967. return true;
  100968. }
  100969. return false;
  100970. };
  100971. NullEngine.prototype._bindTexture = function (channel, texture) {
  100972. if (channel < 0) {
  100973. return;
  100974. }
  100975. this._bindTextureDirectly(0, texture);
  100976. };
  100977. NullEngine.prototype._releaseBuffer = function (buffer) {
  100978. buffer.references--;
  100979. if (buffer.references === 0) {
  100980. return true;
  100981. }
  100982. return false;
  100983. };
  100984. NullEngine.prototype.releaseEffects = function () {
  100985. };
  100986. NullEngine.prototype.displayLoadingUI = function () {
  100987. };
  100988. NullEngine.prototype.hideLoadingUI = function () {
  100989. };
  100990. /** @hidden */
  100991. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  100992. if (faceIndex === void 0) { faceIndex = 0; }
  100993. if (lod === void 0) { lod = 0; }
  100994. };
  100995. /** @hidden */
  100996. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  100997. if (faceIndex === void 0) { faceIndex = 0; }
  100998. if (lod === void 0) { lod = 0; }
  100999. };
  101000. /** @hidden */
  101001. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  101002. if (faceIndex === void 0) { faceIndex = 0; }
  101003. if (lod === void 0) { lod = 0; }
  101004. };
  101005. /** @hidden */
  101006. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  101007. if (faceIndex === void 0) { faceIndex = 0; }
  101008. if (lod === void 0) { lod = 0; }
  101009. };
  101010. return NullEngine;
  101011. }(BABYLON.Engine));
  101012. BABYLON.NullEngine = NullEngine;
  101013. })(BABYLON || (BABYLON = {}));
  101014. //# sourceMappingURL=babylon.nullEngine.js.map
  101015. var BABYLON;
  101016. (function (BABYLON) {
  101017. /**
  101018. * This class can be used to get instrumentation data from a Babylon engine
  101019. */
  101020. var EngineInstrumentation = /** @class */ (function () {
  101021. function EngineInstrumentation(engine) {
  101022. this.engine = engine;
  101023. this._captureGPUFrameTime = false;
  101024. this._gpuFrameTime = new BABYLON.PerfCounter();
  101025. this._captureShaderCompilationTime = false;
  101026. this._shaderCompilationTime = new BABYLON.PerfCounter();
  101027. // Observers
  101028. this._onBeginFrameObserver = null;
  101029. this._onEndFrameObserver = null;
  101030. this._onBeforeShaderCompilationObserver = null;
  101031. this._onAfterShaderCompilationObserver = null;
  101032. }
  101033. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  101034. // Properties
  101035. /**
  101036. * Gets the perf counter used for GPU frame time
  101037. */
  101038. get: function () {
  101039. return this._gpuFrameTime;
  101040. },
  101041. enumerable: true,
  101042. configurable: true
  101043. });
  101044. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  101045. /**
  101046. * Gets the GPU frame time capture status
  101047. */
  101048. get: function () {
  101049. return this._captureGPUFrameTime;
  101050. },
  101051. /**
  101052. * Enable or disable the GPU frame time capture
  101053. */
  101054. set: function (value) {
  101055. var _this = this;
  101056. if (value === this._captureGPUFrameTime) {
  101057. return;
  101058. }
  101059. this._captureGPUFrameTime = value;
  101060. if (value) {
  101061. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  101062. if (!_this._gpuFrameTimeToken) {
  101063. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  101064. }
  101065. });
  101066. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  101067. if (!_this._gpuFrameTimeToken) {
  101068. return;
  101069. }
  101070. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  101071. if (time > -1) {
  101072. _this._gpuFrameTimeToken = null;
  101073. _this._gpuFrameTime.fetchNewFrame();
  101074. _this._gpuFrameTime.addCount(time, true);
  101075. }
  101076. });
  101077. }
  101078. else {
  101079. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101080. this._onBeginFrameObserver = null;
  101081. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101082. this._onEndFrameObserver = null;
  101083. }
  101084. },
  101085. enumerable: true,
  101086. configurable: true
  101087. });
  101088. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  101089. /**
  101090. * Gets the perf counter used for shader compilation time
  101091. */
  101092. get: function () {
  101093. return this._shaderCompilationTime;
  101094. },
  101095. enumerable: true,
  101096. configurable: true
  101097. });
  101098. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  101099. /**
  101100. * Gets the shader compilation time capture status
  101101. */
  101102. get: function () {
  101103. return this._captureShaderCompilationTime;
  101104. },
  101105. /**
  101106. * Enable or disable the shader compilation time capture
  101107. */
  101108. set: function (value) {
  101109. var _this = this;
  101110. if (value === this._captureShaderCompilationTime) {
  101111. return;
  101112. }
  101113. this._captureShaderCompilationTime = value;
  101114. if (value) {
  101115. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  101116. _this._shaderCompilationTime.fetchNewFrame();
  101117. _this._shaderCompilationTime.beginMonitoring();
  101118. });
  101119. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  101120. _this._shaderCompilationTime.endMonitoring();
  101121. });
  101122. }
  101123. else {
  101124. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101125. this._onBeforeShaderCompilationObserver = null;
  101126. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101127. this._onAfterShaderCompilationObserver = null;
  101128. }
  101129. },
  101130. enumerable: true,
  101131. configurable: true
  101132. });
  101133. EngineInstrumentation.prototype.dispose = function () {
  101134. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101135. this._onBeginFrameObserver = null;
  101136. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101137. this._onEndFrameObserver = null;
  101138. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101139. this._onBeforeShaderCompilationObserver = null;
  101140. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101141. this._onAfterShaderCompilationObserver = null;
  101142. this.engine = null;
  101143. };
  101144. return EngineInstrumentation;
  101145. }());
  101146. BABYLON.EngineInstrumentation = EngineInstrumentation;
  101147. })(BABYLON || (BABYLON = {}));
  101148. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  101149. var BABYLON;
  101150. (function (BABYLON) {
  101151. /**
  101152. * This class can be used to get instrumentation data from a Babylon engine
  101153. */
  101154. var SceneInstrumentation = /** @class */ (function () {
  101155. function SceneInstrumentation(scene) {
  101156. var _this = this;
  101157. this.scene = scene;
  101158. this._captureActiveMeshesEvaluationTime = false;
  101159. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  101160. this._captureRenderTargetsRenderTime = false;
  101161. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  101162. this._captureFrameTime = false;
  101163. this._frameTime = new BABYLON.PerfCounter();
  101164. this._captureRenderTime = false;
  101165. this._renderTime = new BABYLON.PerfCounter();
  101166. this._captureInterFrameTime = false;
  101167. this._interFrameTime = new BABYLON.PerfCounter();
  101168. this._captureParticlesRenderTime = false;
  101169. this._particlesRenderTime = new BABYLON.PerfCounter();
  101170. this._captureSpritesRenderTime = false;
  101171. this._spritesRenderTime = new BABYLON.PerfCounter();
  101172. this._capturePhysicsTime = false;
  101173. this._physicsTime = new BABYLON.PerfCounter();
  101174. this._captureAnimationsTime = false;
  101175. this._animationsTime = new BABYLON.PerfCounter();
  101176. this._captureCameraRenderTime = false;
  101177. this._cameraRenderTime = new BABYLON.PerfCounter();
  101178. // Observers
  101179. this._onBeforeActiveMeshesEvaluationObserver = null;
  101180. this._onAfterActiveMeshesEvaluationObserver = null;
  101181. this._onBeforeRenderTargetsRenderObserver = null;
  101182. this._onAfterRenderTargetsRenderObserver = null;
  101183. this._onAfterRenderObserver = null;
  101184. this._onBeforeDrawPhaseObserver = null;
  101185. this._onAfterDrawPhaseObserver = null;
  101186. this._onBeforeAnimationsObserver = null;
  101187. this._onBeforeParticlesRenderingObserver = null;
  101188. this._onAfterParticlesRenderingObserver = null;
  101189. this._onBeforeSpritesRenderingObserver = null;
  101190. this._onAfterSpritesRenderingObserver = null;
  101191. this._onBeforePhysicsObserver = null;
  101192. this._onAfterPhysicsObserver = null;
  101193. this._onAfterAnimationsObserver = null;
  101194. this._onBeforeCameraRenderObserver = null;
  101195. this._onAfterCameraRenderObserver = null;
  101196. // Before render
  101197. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101198. if (_this._captureActiveMeshesEvaluationTime) {
  101199. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101200. }
  101201. if (_this._captureRenderTargetsRenderTime) {
  101202. _this._renderTargetsRenderTime.fetchNewFrame();
  101203. }
  101204. if (_this._captureFrameTime) {
  101205. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101206. _this._frameTime.beginMonitoring();
  101207. }
  101208. if (_this._captureInterFrameTime) {
  101209. _this._interFrameTime.endMonitoring();
  101210. }
  101211. if (_this._captureParticlesRenderTime) {
  101212. _this._particlesRenderTime.fetchNewFrame();
  101213. }
  101214. if (_this._captureSpritesRenderTime) {
  101215. _this._spritesRenderTime.fetchNewFrame();
  101216. }
  101217. if (_this._captureAnimationsTime) {
  101218. _this._animationsTime.beginMonitoring();
  101219. }
  101220. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101221. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101222. });
  101223. // After render
  101224. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101225. if (_this._captureFrameTime) {
  101226. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101227. _this._frameTime.endMonitoring();
  101228. }
  101229. if (_this._captureRenderTime) {
  101230. _this._renderTime.endMonitoring(false);
  101231. }
  101232. if (_this._captureInterFrameTime) {
  101233. _this._interFrameTime.beginMonitoring();
  101234. }
  101235. });
  101236. }
  101237. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101238. // Properties
  101239. /**
  101240. * Gets the perf counter used for active meshes evaluation time
  101241. */
  101242. get: function () {
  101243. return this._activeMeshesEvaluationTime;
  101244. },
  101245. enumerable: true,
  101246. configurable: true
  101247. });
  101248. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101249. /**
  101250. * Gets the active meshes evaluation time capture status
  101251. */
  101252. get: function () {
  101253. return this._captureActiveMeshesEvaluationTime;
  101254. },
  101255. /**
  101256. * Enable or disable the active meshes evaluation time capture
  101257. */
  101258. set: function (value) {
  101259. var _this = this;
  101260. if (value === this._captureActiveMeshesEvaluationTime) {
  101261. return;
  101262. }
  101263. this._captureActiveMeshesEvaluationTime = value;
  101264. if (value) {
  101265. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101266. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101267. _this._activeMeshesEvaluationTime.beginMonitoring();
  101268. });
  101269. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101270. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101271. _this._activeMeshesEvaluationTime.endMonitoring();
  101272. });
  101273. }
  101274. else {
  101275. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101276. this._onBeforeActiveMeshesEvaluationObserver = null;
  101277. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101278. this._onAfterActiveMeshesEvaluationObserver = null;
  101279. }
  101280. },
  101281. enumerable: true,
  101282. configurable: true
  101283. });
  101284. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101285. /**
  101286. * Gets the perf counter used for render targets render time
  101287. */
  101288. get: function () {
  101289. return this._renderTargetsRenderTime;
  101290. },
  101291. enumerable: true,
  101292. configurable: true
  101293. });
  101294. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101295. /**
  101296. * Gets the render targets render time capture status
  101297. */
  101298. get: function () {
  101299. return this._captureRenderTargetsRenderTime;
  101300. },
  101301. /**
  101302. * Enable or disable the render targets render time capture
  101303. */
  101304. set: function (value) {
  101305. var _this = this;
  101306. if (value === this._captureRenderTargetsRenderTime) {
  101307. return;
  101308. }
  101309. this._captureRenderTargetsRenderTime = value;
  101310. if (value) {
  101311. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101312. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101313. _this._renderTargetsRenderTime.beginMonitoring();
  101314. });
  101315. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101316. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101317. _this._renderTargetsRenderTime.endMonitoring(false);
  101318. });
  101319. }
  101320. else {
  101321. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101322. this._onBeforeRenderTargetsRenderObserver = null;
  101323. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101324. this._onAfterRenderTargetsRenderObserver = null;
  101325. }
  101326. },
  101327. enumerable: true,
  101328. configurable: true
  101329. });
  101330. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101331. /**
  101332. * Gets the perf counter used for particles render time
  101333. */
  101334. get: function () {
  101335. return this._particlesRenderTime;
  101336. },
  101337. enumerable: true,
  101338. configurable: true
  101339. });
  101340. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101341. /**
  101342. * Gets the particles render time capture status
  101343. */
  101344. get: function () {
  101345. return this._captureParticlesRenderTime;
  101346. },
  101347. /**
  101348. * Enable or disable the particles render time capture
  101349. */
  101350. set: function (value) {
  101351. var _this = this;
  101352. if (value === this._captureParticlesRenderTime) {
  101353. return;
  101354. }
  101355. this._captureParticlesRenderTime = value;
  101356. if (value) {
  101357. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101358. BABYLON.Tools.StartPerformanceCounter("Particles");
  101359. _this._particlesRenderTime.beginMonitoring();
  101360. });
  101361. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101362. BABYLON.Tools.EndPerformanceCounter("Particles");
  101363. _this._particlesRenderTime.endMonitoring(false);
  101364. });
  101365. }
  101366. else {
  101367. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101368. this._onBeforeParticlesRenderingObserver = null;
  101369. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101370. this._onAfterParticlesRenderingObserver = null;
  101371. }
  101372. },
  101373. enumerable: true,
  101374. configurable: true
  101375. });
  101376. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101377. /**
  101378. * Gets the perf counter used for sprites render time
  101379. */
  101380. get: function () {
  101381. return this._spritesRenderTime;
  101382. },
  101383. enumerable: true,
  101384. configurable: true
  101385. });
  101386. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101387. /**
  101388. * Gets the sprites render time capture status
  101389. */
  101390. get: function () {
  101391. return this._captureSpritesRenderTime;
  101392. },
  101393. /**
  101394. * Enable or disable the sprites render time capture
  101395. */
  101396. set: function (value) {
  101397. var _this = this;
  101398. if (value === this._captureSpritesRenderTime) {
  101399. return;
  101400. }
  101401. this._captureSpritesRenderTime = value;
  101402. if (value) {
  101403. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101404. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101405. _this._spritesRenderTime.beginMonitoring();
  101406. });
  101407. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101408. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101409. _this._spritesRenderTime.endMonitoring(false);
  101410. });
  101411. }
  101412. else {
  101413. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101414. this._onBeforeSpritesRenderingObserver = null;
  101415. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101416. this._onAfterSpritesRenderingObserver = null;
  101417. }
  101418. },
  101419. enumerable: true,
  101420. configurable: true
  101421. });
  101422. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101423. /**
  101424. * Gets the perf counter used for physics time
  101425. */
  101426. get: function () {
  101427. return this._physicsTime;
  101428. },
  101429. enumerable: true,
  101430. configurable: true
  101431. });
  101432. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101433. /**
  101434. * Gets the physics time capture status
  101435. */
  101436. get: function () {
  101437. return this._capturePhysicsTime;
  101438. },
  101439. /**
  101440. * Enable or disable the physics time capture
  101441. */
  101442. set: function (value) {
  101443. var _this = this;
  101444. if (value === this._capturePhysicsTime) {
  101445. return;
  101446. }
  101447. this._capturePhysicsTime = value;
  101448. if (value) {
  101449. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101450. BABYLON.Tools.StartPerformanceCounter("Physics");
  101451. _this._physicsTime.beginMonitoring();
  101452. });
  101453. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101454. BABYLON.Tools.EndPerformanceCounter("Physics");
  101455. _this._physicsTime.endMonitoring();
  101456. });
  101457. }
  101458. else {
  101459. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101460. this._onBeforePhysicsObserver = null;
  101461. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101462. this._onAfterPhysicsObserver = null;
  101463. }
  101464. },
  101465. enumerable: true,
  101466. configurable: true
  101467. });
  101468. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101469. /**
  101470. * Gets the perf counter used for animations time
  101471. */
  101472. get: function () {
  101473. return this._animationsTime;
  101474. },
  101475. enumerable: true,
  101476. configurable: true
  101477. });
  101478. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101479. /**
  101480. * Gets the animations time capture status
  101481. */
  101482. get: function () {
  101483. return this._captureAnimationsTime;
  101484. },
  101485. /**
  101486. * Enable or disable the animations time capture
  101487. */
  101488. set: function (value) {
  101489. var _this = this;
  101490. if (value === this._captureAnimationsTime) {
  101491. return;
  101492. }
  101493. this._captureAnimationsTime = value;
  101494. if (value) {
  101495. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101496. _this._animationsTime.endMonitoring();
  101497. });
  101498. }
  101499. else {
  101500. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101501. this._onAfterAnimationsObserver = null;
  101502. }
  101503. },
  101504. enumerable: true,
  101505. configurable: true
  101506. });
  101507. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101508. /**
  101509. * Gets the perf counter used for frame time capture
  101510. */
  101511. get: function () {
  101512. return this._frameTime;
  101513. },
  101514. enumerable: true,
  101515. configurable: true
  101516. });
  101517. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101518. /**
  101519. * Gets the frame time capture status
  101520. */
  101521. get: function () {
  101522. return this._captureFrameTime;
  101523. },
  101524. /**
  101525. * Enable or disable the frame time capture
  101526. */
  101527. set: function (value) {
  101528. this._captureFrameTime = value;
  101529. },
  101530. enumerable: true,
  101531. configurable: true
  101532. });
  101533. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101534. /**
  101535. * Gets the perf counter used for inter-frames time capture
  101536. */
  101537. get: function () {
  101538. return this._interFrameTime;
  101539. },
  101540. enumerable: true,
  101541. configurable: true
  101542. });
  101543. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101544. /**
  101545. * Gets the inter-frames time capture status
  101546. */
  101547. get: function () {
  101548. return this._captureInterFrameTime;
  101549. },
  101550. /**
  101551. * Enable or disable the inter-frames time capture
  101552. */
  101553. set: function (value) {
  101554. this._captureInterFrameTime = value;
  101555. },
  101556. enumerable: true,
  101557. configurable: true
  101558. });
  101559. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101560. /**
  101561. * Gets the perf counter used for render time capture
  101562. */
  101563. get: function () {
  101564. return this._renderTime;
  101565. },
  101566. enumerable: true,
  101567. configurable: true
  101568. });
  101569. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101570. /**
  101571. * Gets the render time capture status
  101572. */
  101573. get: function () {
  101574. return this._captureRenderTime;
  101575. },
  101576. /**
  101577. * Enable or disable the render time capture
  101578. */
  101579. set: function (value) {
  101580. var _this = this;
  101581. if (value === this._captureRenderTime) {
  101582. return;
  101583. }
  101584. this._captureRenderTime = value;
  101585. if (value) {
  101586. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101587. _this._renderTime.beginMonitoring();
  101588. BABYLON.Tools.StartPerformanceCounter("Main render");
  101589. });
  101590. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101591. _this._renderTime.endMonitoring(false);
  101592. BABYLON.Tools.EndPerformanceCounter("Main render");
  101593. });
  101594. }
  101595. else {
  101596. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101597. this._onBeforeDrawPhaseObserver = null;
  101598. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101599. this._onAfterDrawPhaseObserver = null;
  101600. }
  101601. },
  101602. enumerable: true,
  101603. configurable: true
  101604. });
  101605. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101606. /**
  101607. * Gets the perf counter used for camera render time capture
  101608. */
  101609. get: function () {
  101610. return this._cameraRenderTime;
  101611. },
  101612. enumerable: true,
  101613. configurable: true
  101614. });
  101615. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101616. /**
  101617. * Gets the camera render time capture status
  101618. */
  101619. get: function () {
  101620. return this._captureCameraRenderTime;
  101621. },
  101622. /**
  101623. * Enable or disable the camera render time capture
  101624. */
  101625. set: function (value) {
  101626. var _this = this;
  101627. if (value === this._captureCameraRenderTime) {
  101628. return;
  101629. }
  101630. this._captureCameraRenderTime = value;
  101631. if (value) {
  101632. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101633. _this._cameraRenderTime.beginMonitoring();
  101634. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101635. });
  101636. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101637. _this._cameraRenderTime.endMonitoring(false);
  101638. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101639. });
  101640. }
  101641. else {
  101642. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101643. this._onBeforeCameraRenderObserver = null;
  101644. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101645. this._onAfterCameraRenderObserver = null;
  101646. }
  101647. },
  101648. enumerable: true,
  101649. configurable: true
  101650. });
  101651. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101652. /**
  101653. * Gets the perf counter used for draw calls
  101654. */
  101655. get: function () {
  101656. return this.scene.getEngine()._drawCalls;
  101657. },
  101658. enumerable: true,
  101659. configurable: true
  101660. });
  101661. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101662. /**
  101663. * Gets the perf counter used for texture collisions
  101664. */
  101665. get: function () {
  101666. return this.scene.getEngine()._textureCollisions;
  101667. },
  101668. enumerable: true,
  101669. configurable: true
  101670. });
  101671. SceneInstrumentation.prototype.dispose = function () {
  101672. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101673. this._onAfterRenderObserver = null;
  101674. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101675. this._onBeforeActiveMeshesEvaluationObserver = null;
  101676. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101677. this._onAfterActiveMeshesEvaluationObserver = null;
  101678. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101679. this._onBeforeRenderTargetsRenderObserver = null;
  101680. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101681. this._onAfterRenderTargetsRenderObserver = null;
  101682. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101683. this._onBeforeAnimationsObserver = null;
  101684. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101685. this._onBeforeParticlesRenderingObserver = null;
  101686. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101687. this._onAfterParticlesRenderingObserver = null;
  101688. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101689. this._onBeforeSpritesRenderingObserver = null;
  101690. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101691. this._onAfterSpritesRenderingObserver = null;
  101692. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101693. this._onBeforeDrawPhaseObserver = null;
  101694. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101695. this._onAfterDrawPhaseObserver = null;
  101696. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101697. this._onBeforePhysicsObserver = null;
  101698. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101699. this._onAfterPhysicsObserver = null;
  101700. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101701. this._onAfterAnimationsObserver = null;
  101702. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101703. this._onBeforeCameraRenderObserver = null;
  101704. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101705. this._onAfterCameraRenderObserver = null;
  101706. this.scene = null;
  101707. };
  101708. return SceneInstrumentation;
  101709. }());
  101710. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101711. })(BABYLON || (BABYLON = {}));
  101712. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101713. var BABYLON;
  101714. (function (BABYLON) {
  101715. /**
  101716. * @hidden
  101717. **/
  101718. var _TimeToken = /** @class */ (function () {
  101719. function _TimeToken() {
  101720. this._timeElapsedQueryEnded = false;
  101721. }
  101722. return _TimeToken;
  101723. }());
  101724. BABYLON._TimeToken = _TimeToken;
  101725. })(BABYLON || (BABYLON = {}));
  101726. //# sourceMappingURL=babylon.timeToken.js.map
  101727. var BABYLON;
  101728. (function (BABYLON) {
  101729. /**
  101730. * Background material defines definition.
  101731. * @hidden Mainly internal Use
  101732. */
  101733. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101734. __extends(BackgroundMaterialDefines, _super);
  101735. /**
  101736. * Constructor of the defines.
  101737. */
  101738. function BackgroundMaterialDefines() {
  101739. var _this = _super.call(this) || this;
  101740. /**
  101741. * True if the diffuse texture is in use.
  101742. */
  101743. _this.DIFFUSE = false;
  101744. /**
  101745. * The direct UV channel to use.
  101746. */
  101747. _this.DIFFUSEDIRECTUV = 0;
  101748. /**
  101749. * True if the diffuse texture is in gamma space.
  101750. */
  101751. _this.GAMMADIFFUSE = false;
  101752. /**
  101753. * True if the diffuse texture has opacity in the alpha channel.
  101754. */
  101755. _this.DIFFUSEHASALPHA = false;
  101756. /**
  101757. * True if you want the material to fade to transparent at grazing angle.
  101758. */
  101759. _this.OPACITYFRESNEL = false;
  101760. /**
  101761. * True if an extra blur needs to be added in the reflection.
  101762. */
  101763. _this.REFLECTIONBLUR = false;
  101764. /**
  101765. * True if you want the material to fade to reflection at grazing angle.
  101766. */
  101767. _this.REFLECTIONFRESNEL = false;
  101768. /**
  101769. * True if you want the material to falloff as far as you move away from the scene center.
  101770. */
  101771. _this.REFLECTIONFALLOFF = false;
  101772. /**
  101773. * False if the current Webgl implementation does not support the texture lod extension.
  101774. */
  101775. _this.TEXTURELODSUPPORT = false;
  101776. /**
  101777. * True to ensure the data are premultiplied.
  101778. */
  101779. _this.PREMULTIPLYALPHA = false;
  101780. /**
  101781. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101782. */
  101783. _this.USERGBCOLOR = false;
  101784. /**
  101785. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101786. * stays aligned with the desired configuration.
  101787. */
  101788. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101789. /**
  101790. * True to add noise in order to reduce the banding effect.
  101791. */
  101792. _this.NOISE = false;
  101793. /**
  101794. * is the reflection texture in BGR color scheme?
  101795. * Mainly used to solve a bug in ios10 video tag
  101796. */
  101797. _this.REFLECTIONBGR = false;
  101798. _this.IMAGEPROCESSING = false;
  101799. _this.VIGNETTE = false;
  101800. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101801. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101802. _this.TONEMAPPING = false;
  101803. _this.CONTRAST = false;
  101804. _this.COLORCURVES = false;
  101805. _this.COLORGRADING = false;
  101806. _this.COLORGRADING3D = false;
  101807. _this.SAMPLER3DGREENDEPTH = false;
  101808. _this.SAMPLER3DBGRMAP = false;
  101809. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101810. _this.EXPOSURE = false;
  101811. // Reflection.
  101812. _this.REFLECTION = false;
  101813. _this.REFLECTIONMAP_3D = false;
  101814. _this.REFLECTIONMAP_SPHERICAL = false;
  101815. _this.REFLECTIONMAP_PLANAR = false;
  101816. _this.REFLECTIONMAP_CUBIC = false;
  101817. _this.REFLECTIONMAP_PROJECTION = false;
  101818. _this.REFLECTIONMAP_SKYBOX = false;
  101819. _this.REFLECTIONMAP_EXPLICIT = false;
  101820. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101821. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101822. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101823. _this.INVERTCUBICMAP = false;
  101824. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101825. _this.LODINREFLECTIONALPHA = false;
  101826. _this.GAMMAREFLECTION = false;
  101827. _this.RGBDREFLECTION = false;
  101828. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101829. // Default BJS.
  101830. _this.MAINUV1 = false;
  101831. _this.MAINUV2 = false;
  101832. _this.UV1 = false;
  101833. _this.UV2 = false;
  101834. _this.CLIPPLANE = false;
  101835. _this.POINTSIZE = false;
  101836. _this.FOG = false;
  101837. _this.NORMAL = false;
  101838. _this.NUM_BONE_INFLUENCERS = 0;
  101839. _this.BonesPerMesh = 0;
  101840. _this.INSTANCES = false;
  101841. _this.SHADOWFLOAT = false;
  101842. _this.rebuild();
  101843. return _this;
  101844. }
  101845. return BackgroundMaterialDefines;
  101846. }(BABYLON.MaterialDefines));
  101847. /**
  101848. * Background material used to create an efficient environement around your scene.
  101849. */
  101850. var BackgroundMaterial = /** @class */ (function (_super) {
  101851. __extends(BackgroundMaterial, _super);
  101852. /**
  101853. * Instantiates a Background Material in the given scene
  101854. * @param name The friendly name of the material
  101855. * @param scene The scene to add the material to
  101856. */
  101857. function BackgroundMaterial(name, scene) {
  101858. var _this = _super.call(this, name, scene) || this;
  101859. /**
  101860. * Key light Color (multiply against the environement texture)
  101861. */
  101862. _this.primaryColor = BABYLON.Color3.White();
  101863. _this._primaryColorShadowLevel = 0;
  101864. _this._primaryColorHighlightLevel = 0;
  101865. /**
  101866. * Reflection Texture used in the material.
  101867. * Should be author in a specific way for the best result (refer to the documentation).
  101868. */
  101869. _this.reflectionTexture = null;
  101870. /**
  101871. * Reflection Texture level of blur.
  101872. *
  101873. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101874. * texture twice.
  101875. */
  101876. _this.reflectionBlur = 0;
  101877. /**
  101878. * Diffuse Texture used in the material.
  101879. * Should be author in a specific way for the best result (refer to the documentation).
  101880. */
  101881. _this.diffuseTexture = null;
  101882. _this._shadowLights = null;
  101883. /**
  101884. * Specify the list of lights casting shadow on the material.
  101885. * All scene shadow lights will be included if null.
  101886. */
  101887. _this.shadowLights = null;
  101888. /**
  101889. * Helps adjusting the shadow to a softer level if required.
  101890. * 0 means black shadows and 1 means no shadows.
  101891. */
  101892. _this.shadowLevel = 0;
  101893. /**
  101894. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101895. * It is usually zero but might be interesting to modify according to your setup.
  101896. */
  101897. _this.sceneCenter = BABYLON.Vector3.Zero();
  101898. /**
  101899. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101900. * This helps ensuring a nice transition when the camera goes under the ground.
  101901. */
  101902. _this.opacityFresnel = true;
  101903. /**
  101904. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101905. * This helps adding a mirror texture on the ground.
  101906. */
  101907. _this.reflectionFresnel = false;
  101908. /**
  101909. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101910. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101911. */
  101912. _this.reflectionFalloffDistance = 0.0;
  101913. /**
  101914. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101915. */
  101916. _this.reflectionAmount = 1.0;
  101917. /**
  101918. * This specifies the weight of the reflection at grazing angle.
  101919. */
  101920. _this.reflectionReflectance0 = 0.05;
  101921. /**
  101922. * This specifies the weight of the reflection at a perpendicular point of view.
  101923. */
  101924. _this.reflectionReflectance90 = 0.5;
  101925. /**
  101926. * Helps to directly use the maps channels instead of their level.
  101927. */
  101928. _this.useRGBColor = true;
  101929. /**
  101930. * This helps reducing the banding effect that could occur on the background.
  101931. */
  101932. _this.enableNoise = false;
  101933. _this._fovMultiplier = 1.0;
  101934. /**
  101935. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101936. */
  101937. _this.useEquirectangularFOV = false;
  101938. _this._maxSimultaneousLights = 4;
  101939. /**
  101940. * Number of Simultaneous lights allowed on the material.
  101941. */
  101942. _this.maxSimultaneousLights = 4;
  101943. /**
  101944. * Keep track of the image processing observer to allow dispose and replace.
  101945. */
  101946. _this._imageProcessingObserver = null;
  101947. /**
  101948. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101949. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101950. */
  101951. _this.switchToBGR = false;
  101952. // Temp values kept as cache in the material.
  101953. _this._renderTargets = new BABYLON.SmartArray(16);
  101954. _this._reflectionControls = BABYLON.Vector4.Zero();
  101955. _this._white = BABYLON.Color3.White();
  101956. _this._primaryShadowColor = BABYLON.Color3.Black();
  101957. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101958. // Setup the default processing configuration to the scene.
  101959. _this._attachImageProcessingConfiguration(null);
  101960. _this.getRenderTargetTextures = function () {
  101961. _this._renderTargets.reset();
  101962. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101963. _this._renderTargets.push(_this._diffuseTexture);
  101964. }
  101965. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101966. _this._renderTargets.push(_this._reflectionTexture);
  101967. }
  101968. return _this._renderTargets;
  101969. };
  101970. return _this;
  101971. }
  101972. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101973. /**
  101974. * Experimental Internal Use Only.
  101975. *
  101976. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101977. * This acts as a helper to set the primary color to a more "human friendly" value.
  101978. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101979. * output color as close as possible from the chosen value.
  101980. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101981. * part of lighting setup.)
  101982. */
  101983. get: function () {
  101984. return this.__perceptualColor;
  101985. },
  101986. set: function (value) {
  101987. this.__perceptualColor = value;
  101988. this._computePrimaryColorFromPerceptualColor();
  101989. this._markAllSubMeshesAsLightsDirty();
  101990. },
  101991. enumerable: true,
  101992. configurable: true
  101993. });
  101994. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101995. /**
  101996. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101997. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101998. */
  101999. get: function () {
  102000. return this._primaryColorShadowLevel;
  102001. },
  102002. set: function (value) {
  102003. this._primaryColorShadowLevel = value;
  102004. this._computePrimaryColors();
  102005. this._markAllSubMeshesAsLightsDirty();
  102006. },
  102007. enumerable: true,
  102008. configurable: true
  102009. });
  102010. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  102011. /**
  102012. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  102013. * The primary color is used at the level chosen to define what the white area would look.
  102014. */
  102015. get: function () {
  102016. return this._primaryColorHighlightLevel;
  102017. },
  102018. set: function (value) {
  102019. this._primaryColorHighlightLevel = value;
  102020. this._computePrimaryColors();
  102021. this._markAllSubMeshesAsLightsDirty();
  102022. },
  102023. enumerable: true,
  102024. configurable: true
  102025. });
  102026. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  102027. /**
  102028. * Sets the reflection reflectance fresnel values according to the default standard
  102029. * empirically know to work well :-)
  102030. */
  102031. set: function (value) {
  102032. var reflectionWeight = value;
  102033. if (reflectionWeight < 0.5) {
  102034. reflectionWeight = reflectionWeight * 2.0;
  102035. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  102036. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  102037. }
  102038. else {
  102039. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  102040. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  102041. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  102042. }
  102043. },
  102044. enumerable: true,
  102045. configurable: true
  102046. });
  102047. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  102048. /**
  102049. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102050. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  102051. * Recommended to be keep at 1.0 except for special cases.
  102052. */
  102053. get: function () {
  102054. return this._fovMultiplier;
  102055. },
  102056. set: function (value) {
  102057. if (isNaN(value)) {
  102058. value = 1.0;
  102059. }
  102060. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  102061. },
  102062. enumerable: true,
  102063. configurable: true
  102064. });
  102065. /**
  102066. * Attaches a new image processing configuration to the PBR Material.
  102067. * @param configuration (if null the scene configuration will be use)
  102068. */
  102069. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  102070. var _this = this;
  102071. if (configuration === this._imageProcessingConfiguration) {
  102072. return;
  102073. }
  102074. // Detaches observer.
  102075. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102076. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102077. }
  102078. // Pick the scene configuration if needed.
  102079. if (!configuration) {
  102080. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  102081. }
  102082. else {
  102083. this._imageProcessingConfiguration = configuration;
  102084. }
  102085. // Attaches observer.
  102086. if (this._imageProcessingConfiguration) {
  102087. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  102088. _this._computePrimaryColorFromPerceptualColor();
  102089. _this._markAllSubMeshesAsImageProcessingDirty();
  102090. });
  102091. }
  102092. };
  102093. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  102094. /**
  102095. * Gets the image processing configuration used either in this material.
  102096. */
  102097. get: function () {
  102098. return this._imageProcessingConfiguration;
  102099. },
  102100. /**
  102101. * Sets the Default image processing configuration used either in the this material.
  102102. *
  102103. * If sets to null, the scene one is in use.
  102104. */
  102105. set: function (value) {
  102106. this._attachImageProcessingConfiguration(value);
  102107. // Ensure the effect will be rebuilt.
  102108. this._markAllSubMeshesAsTexturesDirty();
  102109. },
  102110. enumerable: true,
  102111. configurable: true
  102112. });
  102113. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  102114. /**
  102115. * Gets wether the color curves effect is enabled.
  102116. */
  102117. get: function () {
  102118. return this.imageProcessingConfiguration.colorCurvesEnabled;
  102119. },
  102120. /**
  102121. * Sets wether the color curves effect is enabled.
  102122. */
  102123. set: function (value) {
  102124. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  102125. },
  102126. enumerable: true,
  102127. configurable: true
  102128. });
  102129. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  102130. /**
  102131. * Gets wether the color grading effect is enabled.
  102132. */
  102133. get: function () {
  102134. return this.imageProcessingConfiguration.colorGradingEnabled;
  102135. },
  102136. /**
  102137. * Gets wether the color grading effect is enabled.
  102138. */
  102139. set: function (value) {
  102140. this.imageProcessingConfiguration.colorGradingEnabled = value;
  102141. },
  102142. enumerable: true,
  102143. configurable: true
  102144. });
  102145. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  102146. /**
  102147. * Gets wether tonemapping is enabled or not.
  102148. */
  102149. get: function () {
  102150. return this._imageProcessingConfiguration.toneMappingEnabled;
  102151. },
  102152. /**
  102153. * Sets wether tonemapping is enabled or not
  102154. */
  102155. set: function (value) {
  102156. this._imageProcessingConfiguration.toneMappingEnabled = value;
  102157. },
  102158. enumerable: true,
  102159. configurable: true
  102160. });
  102161. ;
  102162. ;
  102163. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  102164. /**
  102165. * The camera exposure used on this material.
  102166. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102167. * This corresponds to a photographic exposure.
  102168. */
  102169. get: function () {
  102170. return this._imageProcessingConfiguration.exposure;
  102171. },
  102172. /**
  102173. * The camera exposure used on this material.
  102174. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102175. * This corresponds to a photographic exposure.
  102176. */
  102177. set: function (value) {
  102178. this._imageProcessingConfiguration.exposure = value;
  102179. },
  102180. enumerable: true,
  102181. configurable: true
  102182. });
  102183. ;
  102184. ;
  102185. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  102186. /**
  102187. * Gets The camera contrast used on this material.
  102188. */
  102189. get: function () {
  102190. return this._imageProcessingConfiguration.contrast;
  102191. },
  102192. /**
  102193. * Sets The camera contrast used on this material.
  102194. */
  102195. set: function (value) {
  102196. this._imageProcessingConfiguration.contrast = value;
  102197. },
  102198. enumerable: true,
  102199. configurable: true
  102200. });
  102201. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102202. /**
  102203. * Gets the Color Grading 2D Lookup Texture.
  102204. */
  102205. get: function () {
  102206. return this._imageProcessingConfiguration.colorGradingTexture;
  102207. },
  102208. /**
  102209. * Sets the Color Grading 2D Lookup Texture.
  102210. */
  102211. set: function (value) {
  102212. this.imageProcessingConfiguration.colorGradingTexture = value;
  102213. },
  102214. enumerable: true,
  102215. configurable: true
  102216. });
  102217. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102218. /**
  102219. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102220. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102221. * 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;
  102222. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102223. */
  102224. get: function () {
  102225. return this.imageProcessingConfiguration.colorCurves;
  102226. },
  102227. /**
  102228. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102229. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102230. * 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;
  102231. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102232. */
  102233. set: function (value) {
  102234. this.imageProcessingConfiguration.colorCurves = value;
  102235. },
  102236. enumerable: true,
  102237. configurable: true
  102238. });
  102239. /**
  102240. * The entire material has been created in order to prevent overdraw.
  102241. * @returns false
  102242. */
  102243. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102244. return true;
  102245. };
  102246. /**
  102247. * The entire material has been created in order to prevent overdraw.
  102248. * @returns true if blending is enable
  102249. */
  102250. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102251. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102252. };
  102253. /**
  102254. * Checks wether the material is ready to be rendered for a given mesh.
  102255. * @param mesh The mesh to render
  102256. * @param subMesh The submesh to check against
  102257. * @param useInstances Specify wether or not the material is used with instances
  102258. * @returns true if all the dependencies are ready (Textures, Effects...)
  102259. */
  102260. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102261. var _this = this;
  102262. if (useInstances === void 0) { useInstances = false; }
  102263. if (subMesh.effect && this.isFrozen) {
  102264. if (this._wasPreviouslyReady) {
  102265. return true;
  102266. }
  102267. }
  102268. if (!subMesh._materialDefines) {
  102269. subMesh._materialDefines = new BackgroundMaterialDefines();
  102270. }
  102271. var scene = this.getScene();
  102272. var defines = subMesh._materialDefines;
  102273. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102274. if (defines._renderId === scene.getRenderId()) {
  102275. return true;
  102276. }
  102277. }
  102278. var engine = scene.getEngine();
  102279. // Lights
  102280. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102281. defines._needNormals = true;
  102282. // Textures
  102283. if (defines._areTexturesDirty) {
  102284. defines._needUVs = false;
  102285. if (scene.texturesEnabled) {
  102286. if (scene.getEngine().getCaps().textureLOD) {
  102287. defines.TEXTURELODSUPPORT = true;
  102288. }
  102289. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102290. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102291. return false;
  102292. }
  102293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102294. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102295. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102296. defines.OPACITYFRESNEL = this._opacityFresnel;
  102297. }
  102298. else {
  102299. defines.DIFFUSE = false;
  102300. defines.DIFFUSEHASALPHA = false;
  102301. defines.GAMMADIFFUSE = false;
  102302. defines.OPACITYFRESNEL = false;
  102303. }
  102304. var reflectionTexture = this._reflectionTexture;
  102305. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102306. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102307. return false;
  102308. }
  102309. defines.REFLECTION = true;
  102310. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102311. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102312. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102313. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102314. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102315. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102316. defines.REFLECTIONBGR = this.switchToBGR;
  102317. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102318. defines.INVERTCUBICMAP = true;
  102319. }
  102320. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102321. switch (reflectionTexture.coordinatesMode) {
  102322. case BABYLON.Texture.EXPLICIT_MODE:
  102323. defines.REFLECTIONMAP_EXPLICIT = true;
  102324. break;
  102325. case BABYLON.Texture.PLANAR_MODE:
  102326. defines.REFLECTIONMAP_PLANAR = true;
  102327. break;
  102328. case BABYLON.Texture.PROJECTION_MODE:
  102329. defines.REFLECTIONMAP_PROJECTION = true;
  102330. break;
  102331. case BABYLON.Texture.SKYBOX_MODE:
  102332. defines.REFLECTIONMAP_SKYBOX = true;
  102333. break;
  102334. case BABYLON.Texture.SPHERICAL_MODE:
  102335. defines.REFLECTIONMAP_SPHERICAL = true;
  102336. break;
  102337. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102338. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102339. break;
  102340. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102341. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102342. break;
  102343. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102344. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102345. break;
  102346. case BABYLON.Texture.CUBIC_MODE:
  102347. case BABYLON.Texture.INVCUBIC_MODE:
  102348. default:
  102349. defines.REFLECTIONMAP_CUBIC = true;
  102350. break;
  102351. }
  102352. if (this.reflectionFresnel) {
  102353. defines.REFLECTIONFRESNEL = true;
  102354. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102355. this._reflectionControls.x = this.reflectionAmount;
  102356. this._reflectionControls.y = this.reflectionReflectance0;
  102357. this._reflectionControls.z = this.reflectionReflectance90;
  102358. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102359. }
  102360. else {
  102361. defines.REFLECTIONFRESNEL = false;
  102362. defines.REFLECTIONFALLOFF = false;
  102363. }
  102364. }
  102365. else {
  102366. defines.REFLECTION = false;
  102367. defines.REFLECTIONFRESNEL = false;
  102368. defines.REFLECTIONFALLOFF = false;
  102369. defines.REFLECTIONBLUR = false;
  102370. defines.REFLECTIONMAP_3D = false;
  102371. defines.REFLECTIONMAP_SPHERICAL = false;
  102372. defines.REFLECTIONMAP_PLANAR = false;
  102373. defines.REFLECTIONMAP_CUBIC = false;
  102374. defines.REFLECTIONMAP_PROJECTION = false;
  102375. defines.REFLECTIONMAP_SKYBOX = false;
  102376. defines.REFLECTIONMAP_EXPLICIT = false;
  102377. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102378. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102379. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102380. defines.INVERTCUBICMAP = false;
  102381. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102382. defines.LODINREFLECTIONALPHA = false;
  102383. defines.GAMMAREFLECTION = false;
  102384. defines.RGBDREFLECTION = false;
  102385. }
  102386. }
  102387. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102388. defines.USERGBCOLOR = this._useRGBColor;
  102389. defines.NOISE = this._enableNoise;
  102390. }
  102391. if (defines._areLightsDirty) {
  102392. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102393. }
  102394. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102395. if (!this._imageProcessingConfiguration.isReady()) {
  102396. return false;
  102397. }
  102398. this._imageProcessingConfiguration.prepareDefines(defines);
  102399. }
  102400. // Misc.
  102401. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102402. // Values that need to be evaluated on every frame
  102403. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102404. // Attribs
  102405. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102406. if (mesh) {
  102407. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102408. mesh.createNormals(true);
  102409. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102410. }
  102411. }
  102412. }
  102413. // Get correct effect
  102414. if (defines.isDirty) {
  102415. defines.markAsProcessed();
  102416. scene.resetCachedMaterial();
  102417. // Fallbacks
  102418. var fallbacks = new BABYLON.EffectFallbacks();
  102419. if (defines.FOG) {
  102420. fallbacks.addFallback(0, "FOG");
  102421. }
  102422. if (defines.POINTSIZE) {
  102423. fallbacks.addFallback(1, "POINTSIZE");
  102424. }
  102425. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102426. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102427. fallbacks.addCPUSkinningFallback(0, mesh);
  102428. }
  102429. //Attributes
  102430. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102431. if (defines.NORMAL) {
  102432. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102433. }
  102434. if (defines.UV1) {
  102435. attribs.push(BABYLON.VertexBuffer.UVKind);
  102436. }
  102437. if (defines.UV2) {
  102438. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102439. }
  102440. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102441. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102442. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102443. "vFogInfos", "vFogColor", "pointSize",
  102444. "vClipPlane", "mBones",
  102445. "vPrimaryColor", "vPrimaryColorShadow",
  102446. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102447. "shadowLevel", "alpha",
  102448. "vBackgroundCenter", "vReflectionControl",
  102449. "vDiffuseInfos", "diffuseMatrix",
  102450. ];
  102451. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102452. var uniformBuffers = ["Material", "Scene"];
  102453. if (BABYLON.ImageProcessingConfiguration) {
  102454. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102455. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102456. }
  102457. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102458. uniformsNames: uniforms,
  102459. uniformBuffersNames: uniformBuffers,
  102460. samplers: samplers,
  102461. defines: defines,
  102462. maxSimultaneousLights: this._maxSimultaneousLights
  102463. });
  102464. var onCompiled = function (effect) {
  102465. if (_this.onCompiled) {
  102466. _this.onCompiled(effect);
  102467. }
  102468. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102469. };
  102470. var join = defines.toString();
  102471. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102472. attributes: attribs,
  102473. uniformsNames: uniforms,
  102474. uniformBuffersNames: uniformBuffers,
  102475. samplers: samplers,
  102476. defines: join,
  102477. fallbacks: fallbacks,
  102478. onCompiled: onCompiled,
  102479. onError: this.onError,
  102480. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102481. }, engine), defines);
  102482. this.buildUniformLayout();
  102483. }
  102484. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102485. return false;
  102486. }
  102487. defines._renderId = scene.getRenderId();
  102488. this._wasPreviouslyReady = true;
  102489. return true;
  102490. };
  102491. /**
  102492. * Compute the primary color according to the chosen perceptual color.
  102493. */
  102494. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102495. if (!this.__perceptualColor) {
  102496. return;
  102497. }
  102498. this._primaryColor.copyFrom(this.__perceptualColor);
  102499. // Revert gamma space.
  102500. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102501. // Revert image processing configuration.
  102502. if (this._imageProcessingConfiguration) {
  102503. // Revert Exposure.
  102504. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102505. }
  102506. this._computePrimaryColors();
  102507. };
  102508. /**
  102509. * Compute the highlights and shadow colors according to their chosen levels.
  102510. */
  102511. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102512. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102513. return;
  102514. }
  102515. // Find the highlight color based on the configuration.
  102516. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102517. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102518. // Find the shadow color based on the configuration.
  102519. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102520. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102521. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102522. };
  102523. /**
  102524. * Build the uniform buffer used in the material.
  102525. */
  102526. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102527. // Order is important !
  102528. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102529. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102530. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102531. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102532. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102533. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102534. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102535. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102536. this._uniformBuffer.addUniform("pointSize", 1);
  102537. this._uniformBuffer.addUniform("shadowLevel", 1);
  102538. this._uniformBuffer.addUniform("alpha", 1);
  102539. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102540. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102541. this._uniformBuffer.create();
  102542. };
  102543. /**
  102544. * Unbind the material.
  102545. */
  102546. BackgroundMaterial.prototype.unbind = function () {
  102547. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102548. this._uniformBuffer.setTexture("diffuseSampler", null);
  102549. }
  102550. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102551. this._uniformBuffer.setTexture("reflectionSampler", null);
  102552. }
  102553. _super.prototype.unbind.call(this);
  102554. };
  102555. /**
  102556. * Bind only the world matrix to the material.
  102557. * @param world The world matrix to bind.
  102558. */
  102559. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102560. this._activeEffect.setMatrix("world", world);
  102561. };
  102562. /**
  102563. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102564. * @param world The world matrix to bind.
  102565. * @param subMesh The submesh to bind for.
  102566. */
  102567. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102568. var scene = this.getScene();
  102569. var defines = subMesh._materialDefines;
  102570. if (!defines) {
  102571. return;
  102572. }
  102573. var effect = subMesh.effect;
  102574. if (!effect) {
  102575. return;
  102576. }
  102577. this._activeEffect = effect;
  102578. // Matrices
  102579. this.bindOnlyWorldMatrix(world);
  102580. // Bones
  102581. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102582. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102583. if (mustRebind) {
  102584. this._uniformBuffer.bindToEffect(effect, "Material");
  102585. this.bindViewProjection(effect);
  102586. var reflectionTexture = this._reflectionTexture;
  102587. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102588. // Texture uniforms
  102589. if (scene.texturesEnabled) {
  102590. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102591. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102592. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102593. }
  102594. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102595. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102596. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102597. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102598. }
  102599. }
  102600. if (this.shadowLevel > 0) {
  102601. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102602. }
  102603. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102604. // Point size
  102605. if (this.pointsCloud) {
  102606. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102607. }
  102608. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102609. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102610. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102611. }
  102612. else {
  102613. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102614. }
  102615. }
  102616. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102617. // Textures
  102618. if (scene.texturesEnabled) {
  102619. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102620. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102621. }
  102622. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102623. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102624. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102625. }
  102626. else if (!defines.REFLECTIONBLUR) {
  102627. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102628. }
  102629. else {
  102630. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102631. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102632. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102633. }
  102634. if (defines.REFLECTIONFRESNEL) {
  102635. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102636. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102637. }
  102638. }
  102639. }
  102640. // Clip plane
  102641. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102642. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102643. }
  102644. if (mustRebind || !this.isFrozen) {
  102645. if (scene.lightsEnabled) {
  102646. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102647. }
  102648. // View
  102649. this.bindView(effect);
  102650. // Fog
  102651. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102652. // image processing
  102653. if (this._imageProcessingConfiguration) {
  102654. this._imageProcessingConfiguration.bind(this._activeEffect);
  102655. }
  102656. }
  102657. this._uniformBuffer.update();
  102658. this._afterBind(mesh, this._activeEffect);
  102659. };
  102660. /**
  102661. * Dispose the material.
  102662. * @param forceDisposeEffect Force disposal of the associated effect.
  102663. * @param forceDisposeTextures Force disposal of the associated textures.
  102664. */
  102665. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102666. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102667. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102668. if (forceDisposeTextures) {
  102669. if (this.diffuseTexture) {
  102670. this.diffuseTexture.dispose();
  102671. }
  102672. if (this.reflectionTexture) {
  102673. this.reflectionTexture.dispose();
  102674. }
  102675. }
  102676. this._renderTargets.dispose();
  102677. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102678. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102679. }
  102680. _super.prototype.dispose.call(this, forceDisposeEffect);
  102681. };
  102682. /**
  102683. * Clones the material.
  102684. * @param name The cloned name.
  102685. * @returns The cloned material.
  102686. */
  102687. BackgroundMaterial.prototype.clone = function (name) {
  102688. var _this = this;
  102689. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102690. };
  102691. /**
  102692. * Serializes the current material to its JSON representation.
  102693. * @returns The JSON representation.
  102694. */
  102695. BackgroundMaterial.prototype.serialize = function () {
  102696. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102697. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102698. return serializationObject;
  102699. };
  102700. /**
  102701. * Gets the class name of the material
  102702. * @returns "BackgroundMaterial"
  102703. */
  102704. BackgroundMaterial.prototype.getClassName = function () {
  102705. return "BackgroundMaterial";
  102706. };
  102707. /**
  102708. * Parse a JSON input to create back a background material.
  102709. * @param source The JSON data to parse
  102710. * @param scene The scene to create the parsed material in
  102711. * @param rootUrl The root url of the assets the material depends upon
  102712. * @returns the instantiated BackgroundMaterial.
  102713. */
  102714. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102715. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102716. };
  102717. /**
  102718. * Standard reflectance value at parallel view angle.
  102719. */
  102720. BackgroundMaterial.StandardReflectance0 = 0.05;
  102721. /**
  102722. * Standard reflectance value at grazing angle.
  102723. */
  102724. BackgroundMaterial.StandardReflectance90 = 0.5;
  102725. __decorate([
  102726. BABYLON.serializeAsColor3()
  102727. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102728. __decorate([
  102729. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102730. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102731. __decorate([
  102732. BABYLON.serializeAsColor3()
  102733. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102734. __decorate([
  102735. BABYLON.serialize()
  102736. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102737. __decorate([
  102738. BABYLON.serialize()
  102739. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102740. __decorate([
  102741. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102742. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102743. __decorate([
  102744. BABYLON.serializeAsTexture()
  102745. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102746. __decorate([
  102747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102748. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102749. __decorate([
  102750. BABYLON.serialize()
  102751. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102752. __decorate([
  102753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102754. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102755. __decorate([
  102756. BABYLON.serializeAsTexture()
  102757. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102758. __decorate([
  102759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102760. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102761. __decorate([
  102762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102763. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102764. __decorate([
  102765. BABYLON.serialize()
  102766. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102767. __decorate([
  102768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102769. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102770. __decorate([
  102771. BABYLON.serializeAsVector3()
  102772. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102773. __decorate([
  102774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102775. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102776. __decorate([
  102777. BABYLON.serialize()
  102778. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102779. __decorate([
  102780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102781. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102782. __decorate([
  102783. BABYLON.serialize()
  102784. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102785. __decorate([
  102786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102787. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102788. __decorate([
  102789. BABYLON.serialize()
  102790. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102791. __decorate([
  102792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102793. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102794. __decorate([
  102795. BABYLON.serialize()
  102796. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102797. __decorate([
  102798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102799. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102800. __decorate([
  102801. BABYLON.serialize()
  102802. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102803. __decorate([
  102804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102805. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102806. __decorate([
  102807. BABYLON.serialize()
  102808. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102809. __decorate([
  102810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102811. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102812. __decorate([
  102813. BABYLON.serialize()
  102814. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102815. __decorate([
  102816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102817. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102818. __decorate([
  102819. BABYLON.serialize()
  102820. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102821. __decorate([
  102822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102823. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102824. __decorate([
  102825. BABYLON.serialize()
  102826. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102827. __decorate([
  102828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102829. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102830. __decorate([
  102831. BABYLON.serializeAsImageProcessingConfiguration()
  102832. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102833. return BackgroundMaterial;
  102834. }(BABYLON.PushMaterial));
  102835. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102836. })(BABYLON || (BABYLON = {}));
  102837. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102838. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102839. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102840. s = arguments[i];
  102841. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102842. t[p] = s[p];
  102843. }
  102844. return t;
  102845. };
  102846. var BABYLON;
  102847. (function (BABYLON) {
  102848. /**
  102849. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102850. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102851. * It also helps with the default setup of your imageProcessing configuration.
  102852. */
  102853. var EnvironmentHelper = /** @class */ (function () {
  102854. /**
  102855. * constructor
  102856. * @param options
  102857. * @param scene The scene to add the material to
  102858. */
  102859. function EnvironmentHelper(options, scene) {
  102860. var _this = this;
  102861. this._errorHandler = function (message, exception) {
  102862. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102863. };
  102864. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102865. this._scene = scene;
  102866. this.onErrorObservable = new BABYLON.Observable();
  102867. this._setupBackground();
  102868. this._setupImageProcessing();
  102869. }
  102870. /**
  102871. * Creates the default options for the helper.
  102872. */
  102873. EnvironmentHelper._getDefaultOptions = function () {
  102874. return {
  102875. createGround: true,
  102876. groundSize: 15,
  102877. groundTexture: this._groundTextureCDNUrl,
  102878. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102879. groundOpacity: 0.9,
  102880. enableGroundShadow: true,
  102881. groundShadowLevel: 0.5,
  102882. enableGroundMirror: false,
  102883. groundMirrorSizeRatio: 0.3,
  102884. groundMirrorBlurKernel: 64,
  102885. groundMirrorAmount: 1,
  102886. groundMirrorFresnelWeight: 1,
  102887. groundMirrorFallOffDistance: 0,
  102888. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102889. groundYBias: 0.00001,
  102890. createSkybox: true,
  102891. skyboxSize: 20,
  102892. skyboxTexture: this._skyboxTextureCDNUrl,
  102893. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102894. backgroundYRotation: 0,
  102895. sizeAuto: true,
  102896. rootPosition: BABYLON.Vector3.Zero(),
  102897. setupImageProcessing: true,
  102898. environmentTexture: this._environmentTextureCDNUrl,
  102899. cameraExposure: 0.8,
  102900. cameraContrast: 1.2,
  102901. toneMappingEnabled: true,
  102902. };
  102903. };
  102904. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102905. /**
  102906. * Gets the root mesh created by the helper.
  102907. */
  102908. get: function () {
  102909. return this._rootMesh;
  102910. },
  102911. enumerable: true,
  102912. configurable: true
  102913. });
  102914. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102915. /**
  102916. * Gets the skybox created by the helper.
  102917. */
  102918. get: function () {
  102919. return this._skybox;
  102920. },
  102921. enumerable: true,
  102922. configurable: true
  102923. });
  102924. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102925. /**
  102926. * Gets the skybox texture created by the helper.
  102927. */
  102928. get: function () {
  102929. return this._skyboxTexture;
  102930. },
  102931. enumerable: true,
  102932. configurable: true
  102933. });
  102934. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102935. /**
  102936. * Gets the skybox material created by the helper.
  102937. */
  102938. get: function () {
  102939. return this._skyboxMaterial;
  102940. },
  102941. enumerable: true,
  102942. configurable: true
  102943. });
  102944. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102945. /**
  102946. * Gets the ground mesh created by the helper.
  102947. */
  102948. get: function () {
  102949. return this._ground;
  102950. },
  102951. enumerable: true,
  102952. configurable: true
  102953. });
  102954. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102955. /**
  102956. * Gets the ground texture created by the helper.
  102957. */
  102958. get: function () {
  102959. return this._groundTexture;
  102960. },
  102961. enumerable: true,
  102962. configurable: true
  102963. });
  102964. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102965. /**
  102966. * Gets the ground mirror created by the helper.
  102967. */
  102968. get: function () {
  102969. return this._groundMirror;
  102970. },
  102971. enumerable: true,
  102972. configurable: true
  102973. });
  102974. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102975. /**
  102976. * Gets the ground mirror render list to helps pushing the meshes
  102977. * you wish in the ground reflection.
  102978. */
  102979. get: function () {
  102980. if (this._groundMirror) {
  102981. return this._groundMirror.renderList;
  102982. }
  102983. return null;
  102984. },
  102985. enumerable: true,
  102986. configurable: true
  102987. });
  102988. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102989. /**
  102990. * Gets the ground material created by the helper.
  102991. */
  102992. get: function () {
  102993. return this._groundMaterial;
  102994. },
  102995. enumerable: true,
  102996. configurable: true
  102997. });
  102998. /**
  102999. * Updates the background according to the new options
  103000. * @param options
  103001. */
  103002. EnvironmentHelper.prototype.updateOptions = function (options) {
  103003. var newOptions = __assign({}, this._options, options);
  103004. if (this._ground && !newOptions.createGround) {
  103005. this._ground.dispose();
  103006. this._ground = null;
  103007. }
  103008. if (this._groundMaterial && !newOptions.createGround) {
  103009. this._groundMaterial.dispose();
  103010. this._groundMaterial = null;
  103011. }
  103012. if (this._groundTexture) {
  103013. if (this._options.groundTexture != newOptions.groundTexture) {
  103014. this._groundTexture.dispose();
  103015. this._groundTexture = null;
  103016. }
  103017. }
  103018. if (this._skybox && !newOptions.createSkybox) {
  103019. this._skybox.dispose();
  103020. this._skybox = null;
  103021. }
  103022. if (this._skyboxMaterial && !newOptions.createSkybox) {
  103023. this._skyboxMaterial.dispose();
  103024. this._skyboxMaterial = null;
  103025. }
  103026. if (this._skyboxTexture) {
  103027. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  103028. this._skyboxTexture.dispose();
  103029. this._skyboxTexture = null;
  103030. }
  103031. }
  103032. if (this._groundMirror && !newOptions.enableGroundMirror) {
  103033. this._groundMirror.dispose();
  103034. this._groundMirror = null;
  103035. }
  103036. if (this._scene.environmentTexture) {
  103037. if (this._options.environmentTexture != newOptions.environmentTexture) {
  103038. this._scene.environmentTexture.dispose();
  103039. }
  103040. }
  103041. this._options = newOptions;
  103042. this._setupBackground();
  103043. this._setupImageProcessing();
  103044. };
  103045. /**
  103046. * Sets the primary color of all the available elements.
  103047. * @param color the main color to affect to the ground and the background
  103048. */
  103049. EnvironmentHelper.prototype.setMainColor = function (color) {
  103050. if (this.groundMaterial) {
  103051. this.groundMaterial.primaryColor = color;
  103052. }
  103053. if (this.skyboxMaterial) {
  103054. this.skyboxMaterial.primaryColor = color;
  103055. }
  103056. if (this.groundMirror) {
  103057. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  103058. }
  103059. };
  103060. /**
  103061. * Setup the image processing according to the specified options.
  103062. */
  103063. EnvironmentHelper.prototype._setupImageProcessing = function () {
  103064. if (this._options.setupImageProcessing) {
  103065. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  103066. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  103067. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  103068. this._setupEnvironmentTexture();
  103069. }
  103070. };
  103071. /**
  103072. * Setup the environment texture according to the specified options.
  103073. */
  103074. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  103075. if (this._scene.environmentTexture) {
  103076. return;
  103077. }
  103078. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  103079. this._scene.environmentTexture = this._options.environmentTexture;
  103080. return;
  103081. }
  103082. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  103083. this._scene.environmentTexture = environmentTexture;
  103084. };
  103085. /**
  103086. * Setup the background according to the specified options.
  103087. */
  103088. EnvironmentHelper.prototype._setupBackground = function () {
  103089. if (!this._rootMesh) {
  103090. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  103091. }
  103092. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  103093. var sceneSize = this._getSceneSize();
  103094. if (this._options.createGround) {
  103095. this._setupGround(sceneSize);
  103096. this._setupGroundMaterial();
  103097. this._setupGroundDiffuseTexture();
  103098. if (this._options.enableGroundMirror) {
  103099. this._setupGroundMirrorTexture(sceneSize);
  103100. }
  103101. this._setupMirrorInGroundMaterial();
  103102. }
  103103. if (this._options.createSkybox) {
  103104. this._setupSkybox(sceneSize);
  103105. this._setupSkyboxMaterial();
  103106. this._setupSkyboxReflectionTexture();
  103107. }
  103108. this._rootMesh.position.x = sceneSize.rootPosition.x;
  103109. this._rootMesh.position.z = sceneSize.rootPosition.z;
  103110. this._rootMesh.position.y = sceneSize.rootPosition.y;
  103111. };
  103112. /**
  103113. * Get the scene sizes according to the setup.
  103114. */
  103115. EnvironmentHelper.prototype._getSceneSize = function () {
  103116. var _this = this;
  103117. var groundSize = this._options.groundSize;
  103118. var skyboxSize = this._options.skyboxSize;
  103119. var rootPosition = this._options.rootPosition;
  103120. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  103121. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103122. }
  103123. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  103124. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  103125. });
  103126. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  103127. if (this._options.sizeAuto) {
  103128. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  103129. this._scene.activeCamera.upperRadiusLimit) {
  103130. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  103131. skyboxSize = groundSize;
  103132. }
  103133. var sceneDiagonalLenght = sceneDiagonal.length();
  103134. if (sceneDiagonalLenght > groundSize) {
  103135. groundSize = sceneDiagonalLenght * 2;
  103136. skyboxSize = groundSize;
  103137. }
  103138. // 10 % bigger.
  103139. groundSize *= 1.1;
  103140. skyboxSize *= 1.5;
  103141. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  103142. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  103143. }
  103144. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103145. };
  103146. /**
  103147. * Setup the ground according to the specified options.
  103148. */
  103149. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  103150. var _this = this;
  103151. if (!this._ground || this._ground.isDisposed()) {
  103152. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  103153. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  103154. this._ground.parent = this._rootMesh;
  103155. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  103156. }
  103157. this._ground.receiveShadows = this._options.enableGroundShadow;
  103158. };
  103159. /**
  103160. * Setup the ground material according to the specified options.
  103161. */
  103162. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  103163. if (!this._groundMaterial) {
  103164. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  103165. }
  103166. this._groundMaterial.alpha = this._options.groundOpacity;
  103167. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  103168. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  103169. this._groundMaterial.primaryColor = this._options.groundColor;
  103170. this._groundMaterial.useRGBColor = false;
  103171. this._groundMaterial.enableNoise = true;
  103172. if (this._ground) {
  103173. this._ground.material = this._groundMaterial;
  103174. }
  103175. };
  103176. /**
  103177. * Setup the ground diffuse texture according to the specified options.
  103178. */
  103179. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  103180. if (!this._groundMaterial) {
  103181. return;
  103182. }
  103183. if (this._groundTexture) {
  103184. return;
  103185. }
  103186. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  103187. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  103188. return;
  103189. }
  103190. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103191. diffuseTexture.gammaSpace = false;
  103192. diffuseTexture.hasAlpha = true;
  103193. this._groundMaterial.diffuseTexture = diffuseTexture;
  103194. };
  103195. /**
  103196. * Setup the ground mirror texture according to the specified options.
  103197. */
  103198. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103199. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103200. if (!this._groundMirror) {
  103201. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103202. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103203. this._groundMirror.anisotropicFilteringLevel = 1;
  103204. this._groundMirror.wrapU = wrapping;
  103205. this._groundMirror.wrapV = wrapping;
  103206. this._groundMirror.gammaSpace = false;
  103207. if (this._groundMirror.renderList) {
  103208. for (var i = 0; i < this._scene.meshes.length; i++) {
  103209. var mesh = this._scene.meshes[i];
  103210. if (mesh !== this._ground &&
  103211. mesh !== this._skybox &&
  103212. mesh !== this._rootMesh) {
  103213. this._groundMirror.renderList.push(mesh);
  103214. }
  103215. }
  103216. }
  103217. }
  103218. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103219. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103220. };
  103221. /**
  103222. * Setup the ground to receive the mirror texture.
  103223. */
  103224. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103225. if (this._groundMaterial) {
  103226. this._groundMaterial.reflectionTexture = this._groundMirror;
  103227. this._groundMaterial.reflectionFresnel = true;
  103228. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103229. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103230. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103231. }
  103232. };
  103233. /**
  103234. * Setup the skybox according to the specified options.
  103235. */
  103236. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103237. var _this = this;
  103238. if (!this._skybox || this._skybox.isDisposed()) {
  103239. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103240. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103241. }
  103242. this._skybox.parent = this._rootMesh;
  103243. };
  103244. /**
  103245. * Setup the skybox material according to the specified options.
  103246. */
  103247. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103248. if (!this._skybox) {
  103249. return;
  103250. }
  103251. if (!this._skyboxMaterial) {
  103252. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103253. }
  103254. this._skyboxMaterial.useRGBColor = false;
  103255. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103256. this._skyboxMaterial.enableNoise = true;
  103257. this._skybox.material = this._skyboxMaterial;
  103258. };
  103259. /**
  103260. * Setup the skybox reflection texture according to the specified options.
  103261. */
  103262. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103263. if (!this._skyboxMaterial) {
  103264. return;
  103265. }
  103266. if (this._skyboxTexture) {
  103267. return;
  103268. }
  103269. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103270. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103271. return;
  103272. }
  103273. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103274. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103275. this._skyboxTexture.gammaSpace = false;
  103276. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103277. };
  103278. /**
  103279. * Dispose all the elements created by the Helper.
  103280. */
  103281. EnvironmentHelper.prototype.dispose = function () {
  103282. if (this._groundMaterial) {
  103283. this._groundMaterial.dispose(true, true);
  103284. }
  103285. if (this._skyboxMaterial) {
  103286. this._skyboxMaterial.dispose(true, true);
  103287. }
  103288. this._rootMesh.dispose(false);
  103289. };
  103290. /**
  103291. * Default ground texture URL.
  103292. */
  103293. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103294. /**
  103295. * Default skybox texture URL.
  103296. */
  103297. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103298. /**
  103299. * Default environment texture URL.
  103300. */
  103301. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103302. return EnvironmentHelper;
  103303. }());
  103304. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103305. })(BABYLON || (BABYLON = {}));
  103306. //# sourceMappingURL=babylon.environmentHelper.js.map
  103307. var BABYLON;
  103308. (function (BABYLON) {
  103309. /** Internal class used to store shapes for emitters */
  103310. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103311. function ParticleSystemSetEmitterCreationOptions() {
  103312. }
  103313. return ParticleSystemSetEmitterCreationOptions;
  103314. }());
  103315. /**
  103316. * Represents a set of particle systems working together to create a specific effect
  103317. */
  103318. var ParticleSystemSet = /** @class */ (function () {
  103319. function ParticleSystemSet() {
  103320. /**
  103321. * Gets the particle system list
  103322. */
  103323. this.systems = new Array();
  103324. }
  103325. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103326. /**
  103327. * Gets the emitter node used with this set
  103328. */
  103329. get: function () {
  103330. return this._emitterNode;
  103331. },
  103332. enumerable: true,
  103333. configurable: true
  103334. });
  103335. /**
  103336. * Creates a new emitter mesh as a sphere
  103337. * @param options defines the options used to create the sphere
  103338. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103339. * @param scene defines the hosting scene
  103340. */
  103341. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103342. if (this._emitterNode) {
  103343. this._emitterNode.dispose();
  103344. }
  103345. this._emitterCreationOptions = {
  103346. kind: "Sphere",
  103347. options: options,
  103348. renderingGroupId: renderingGroupId
  103349. };
  103350. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103351. emitterMesh.renderingGroupId = renderingGroupId;
  103352. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103353. material.emissiveColor = options.color;
  103354. emitterMesh.material = material;
  103355. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103356. var system = _a[_i];
  103357. system.emitter = emitterMesh;
  103358. }
  103359. this._emitterNode = emitterMesh;
  103360. };
  103361. /**
  103362. * Starts all particle systems of the set
  103363. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103364. */
  103365. ParticleSystemSet.prototype.start = function (emitter) {
  103366. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103367. var system = _a[_i];
  103368. if (emitter) {
  103369. system.emitter = emitter;
  103370. }
  103371. system.start();
  103372. }
  103373. };
  103374. /**
  103375. * Release all associated resources
  103376. */
  103377. ParticleSystemSet.prototype.dispose = function () {
  103378. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103379. var system = _a[_i];
  103380. system.dispose();
  103381. }
  103382. this.systems = [];
  103383. if (this._emitterNode) {
  103384. this._emitterNode.dispose();
  103385. this._emitterNode = null;
  103386. }
  103387. };
  103388. /**
  103389. * Serialize the set into a JSON compatible object
  103390. * @returns a JSON compatible representation of the set
  103391. */
  103392. ParticleSystemSet.prototype.serialize = function () {
  103393. var result = {};
  103394. result.systems = [];
  103395. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103396. var system = _a[_i];
  103397. result.systems.push(system.serialize());
  103398. }
  103399. if (this._emitterNode) {
  103400. result.emitter = this._emitterCreationOptions;
  103401. }
  103402. return result;
  103403. };
  103404. /**
  103405. * Parse a new ParticleSystemSet from a serialized source
  103406. * @param data defines a JSON compatible representation of the set
  103407. * @param scene defines the hosting scene
  103408. * @param gpu defines if we want GPU particles or CPU particles
  103409. * @returns a new ParticleSystemSet
  103410. */
  103411. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103412. if (gpu === void 0) { gpu = false; }
  103413. var result = new ParticleSystemSet();
  103414. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103415. scene = scene || BABYLON.Engine.LastCreatedScene;
  103416. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103417. var system = _a[_i];
  103418. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103419. }
  103420. if (data.emitter) {
  103421. var options = data.emitter.options;
  103422. switch (data.emitter.kind) {
  103423. case "Sphere":
  103424. result.setEmitterAsSphere({
  103425. diameter: options.diameter,
  103426. segments: options.segments,
  103427. color: BABYLON.Color3.FromArray(options.color)
  103428. }, data.emitter.renderingGroupId, scene);
  103429. break;
  103430. }
  103431. }
  103432. return result;
  103433. };
  103434. return ParticleSystemSet;
  103435. }());
  103436. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103437. })(BABYLON || (BABYLON = {}));
  103438. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103439. var BABYLON;
  103440. (function (BABYLON) {
  103441. /**
  103442. * This class is made for on one-liner static method to help creating particle system set.
  103443. */
  103444. var ParticleHelper = /** @class */ (function () {
  103445. function ParticleHelper() {
  103446. }
  103447. /**
  103448. * This is the main static method (one-liner) of this helper to create different particle systems
  103449. * @param type This string represents the type to the particle system to create
  103450. * @param scene The scene where the particle system should live
  103451. * @param gpu If the system will use gpu
  103452. * @returns the ParticleSystemSet created
  103453. */
  103454. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103455. if (gpu === void 0) { gpu = false; }
  103456. if (!scene) {
  103457. scene = BABYLON.Engine.LastCreatedScene;
  103458. ;
  103459. }
  103460. var token = {};
  103461. scene._addPendingData(token);
  103462. return new Promise(function (resolve, reject) {
  103463. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103464. scene._removePendingData(token);
  103465. return reject("Particle system with GPU is not supported.");
  103466. }
  103467. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103468. scene._removePendingData(token);
  103469. var newData = JSON.parse(data.toString());
  103470. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103471. }, undefined, undefined, undefined, function (req, exception) {
  103472. scene._removePendingData(token);
  103473. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103474. });
  103475. });
  103476. };
  103477. /**
  103478. * Static function used to export a particle system to a ParticleSystemSet variable.
  103479. * Please note that the emitter shape is not exported
  103480. * @param system defines the particle systems to export
  103481. */
  103482. ParticleHelper.ExportSet = function (systems) {
  103483. var set = new BABYLON.ParticleSystemSet();
  103484. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103485. var system = systems_1[_i];
  103486. set.systems.push(system);
  103487. }
  103488. return set;
  103489. };
  103490. /**
  103491. * Gets or sets base Assets URL
  103492. */
  103493. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103494. return ParticleHelper;
  103495. }());
  103496. BABYLON.ParticleHelper = ParticleHelper;
  103497. })(BABYLON || (BABYLON = {}));
  103498. //# sourceMappingURL=babylon.particleHelper.js.map
  103499. var BABYLON;
  103500. (function (BABYLON) {
  103501. /**
  103502. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103503. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103504. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103505. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103506. */
  103507. var VideoDome = /** @class */ (function (_super) {
  103508. __extends(VideoDome, _super);
  103509. /**
  103510. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103511. * @param name Element's name, child elements will append suffixes for their own names.
  103512. * @param urlsOrVideo defines the url(s) or the video element to use
  103513. * @param options An object containing optional or exposed sub element properties
  103514. */
  103515. function VideoDome(name, urlsOrVideo, options, scene) {
  103516. var _this = _super.call(this, name, scene) || this;
  103517. _this._useDirectMapping = false;
  103518. // set defaults and manage values
  103519. name = name || "videoDome";
  103520. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103521. options.clickToPlay = Boolean(options.clickToPlay);
  103522. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103523. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103524. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103525. if (options.useDirectMapping === undefined) {
  103526. _this._useDirectMapping = true;
  103527. }
  103528. else {
  103529. _this._useDirectMapping = options.useDirectMapping;
  103530. }
  103531. // create
  103532. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103533. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103534. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103535. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103536. // configure material
  103537. material.useEquirectangularFOV = true;
  103538. material.fovMultiplier = 1.0;
  103539. material.opacityFresnel = false;
  103540. if (_this._useDirectMapping) {
  103541. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103542. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103543. material.diffuseTexture = texture;
  103544. }
  103545. else {
  103546. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103547. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103548. material.reflectionTexture = texture;
  103549. }
  103550. // configure mesh
  103551. _this._mesh.material = material;
  103552. _this._mesh.parent = _this;
  103553. // optional configuration
  103554. if (options.clickToPlay) {
  103555. scene.onPointerUp = function () {
  103556. _this._videoTexture.video.play();
  103557. };
  103558. }
  103559. return _this;
  103560. }
  103561. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103562. /**
  103563. * Gets the video texture being displayed on the sphere
  103564. */
  103565. get: function () {
  103566. return this._videoTexture;
  103567. },
  103568. enumerable: true,
  103569. configurable: true
  103570. });
  103571. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103572. /**
  103573. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103574. * Also see the options.resolution property.
  103575. */
  103576. get: function () {
  103577. return this._material.fovMultiplier;
  103578. },
  103579. set: function (value) {
  103580. this._material.fovMultiplier = value;
  103581. },
  103582. enumerable: true,
  103583. configurable: true
  103584. });
  103585. /**
  103586. * Releases resources associated with this node.
  103587. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103588. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103589. */
  103590. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103591. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103592. this._videoTexture.dispose();
  103593. this._mesh.dispose();
  103594. this._material.dispose();
  103595. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103596. };
  103597. return VideoDome;
  103598. }(BABYLON.Node));
  103599. BABYLON.VideoDome = VideoDome;
  103600. })(BABYLON || (BABYLON = {}));
  103601. //# sourceMappingURL=babylon.videoDome.js.map
  103602. var BABYLON;
  103603. (function (BABYLON) {
  103604. /**
  103605. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103606. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103607. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103608. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103609. */
  103610. var PhotoDome = /** @class */ (function (_super) {
  103611. __extends(PhotoDome, _super);
  103612. /**
  103613. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103614. * @param name Element's name, child elements will append suffixes for their own names.
  103615. * @param urlsOfPhoto define the url of the photo to display
  103616. * @param options An object containing optional or exposed sub element properties
  103617. */
  103618. function PhotoDome(name, urlOfPhoto, options, scene) {
  103619. var _this = _super.call(this, name, scene) || this;
  103620. _this._useDirectMapping = false;
  103621. // set defaults and manage values
  103622. name = name || "photoDome";
  103623. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103624. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103625. if (options.useDirectMapping === undefined) {
  103626. _this._useDirectMapping = true;
  103627. }
  103628. else {
  103629. _this._useDirectMapping = options.useDirectMapping;
  103630. }
  103631. // create
  103632. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103633. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103634. // configure material
  103635. material.opacityFresnel = false;
  103636. material.useEquirectangularFOV = true;
  103637. material.fovMultiplier = 1.0;
  103638. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103639. // configure mesh
  103640. _this._mesh.material = material;
  103641. _this._mesh.parent = _this;
  103642. return _this;
  103643. }
  103644. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103645. /**
  103646. * Gets or sets the texture being displayed on the sphere
  103647. */
  103648. get: function () {
  103649. return this._photoTexture;
  103650. },
  103651. set: function (value) {
  103652. if (this._photoTexture === value) {
  103653. return;
  103654. }
  103655. this._photoTexture = value;
  103656. if (this._useDirectMapping) {
  103657. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103658. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103659. this._material.diffuseTexture = this._photoTexture;
  103660. }
  103661. else {
  103662. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103663. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103664. this._material.reflectionTexture = this._photoTexture;
  103665. }
  103666. },
  103667. enumerable: true,
  103668. configurable: true
  103669. });
  103670. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103671. /**
  103672. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103673. * Also see the options.resolution property.
  103674. */
  103675. get: function () {
  103676. return this._material.fovMultiplier;
  103677. },
  103678. set: function (value) {
  103679. this._material.fovMultiplier = value;
  103680. },
  103681. enumerable: true,
  103682. configurable: true
  103683. });
  103684. /**
  103685. * Releases resources associated with this node.
  103686. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103687. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103688. */
  103689. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103690. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103691. this._photoTexture.dispose();
  103692. this._mesh.dispose();
  103693. this._material.dispose();
  103694. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103695. };
  103696. return PhotoDome;
  103697. }(BABYLON.Node));
  103698. BABYLON.PhotoDome = PhotoDome;
  103699. })(BABYLON || (BABYLON = {}));
  103700. //# sourceMappingURL=babylon.photoDome.js.map
  103701. var BABYLON;
  103702. (function (BABYLON) {
  103703. BABYLON.Engine.prototype.createQuery = function () {
  103704. return this._gl.createQuery();
  103705. };
  103706. BABYLON.Engine.prototype.deleteQuery = function (query) {
  103707. this._gl.deleteQuery(query);
  103708. return this;
  103709. };
  103710. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  103711. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  103712. };
  103713. BABYLON.Engine.prototype.getQueryResult = function (query) {
  103714. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  103715. };
  103716. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  103717. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103718. this._gl.beginQuery(glAlgorithm, query);
  103719. return this;
  103720. };
  103721. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  103722. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103723. this._gl.endQuery(glAlgorithm);
  103724. return this;
  103725. };
  103726. BABYLON.Engine.prototype._createTimeQuery = function () {
  103727. var timerQuery = this.getCaps().timerQuery;
  103728. if (timerQuery.createQueryEXT) {
  103729. return timerQuery.createQueryEXT();
  103730. }
  103731. return this.createQuery();
  103732. };
  103733. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  103734. var timerQuery = this.getCaps().timerQuery;
  103735. if (timerQuery.deleteQueryEXT) {
  103736. timerQuery.deleteQueryEXT(query);
  103737. return;
  103738. }
  103739. this.deleteQuery(query);
  103740. };
  103741. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  103742. var timerQuery = this.getCaps().timerQuery;
  103743. if (timerQuery.getQueryObjectEXT) {
  103744. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  103745. }
  103746. return this.getQueryResult(query);
  103747. };
  103748. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  103749. var timerQuery = this.getCaps().timerQuery;
  103750. if (timerQuery.getQueryObjectEXT) {
  103751. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  103752. }
  103753. return this.isQueryResultAvailable(query);
  103754. };
  103755. BABYLON.Engine.prototype.startTimeQuery = function () {
  103756. var caps = this.getCaps();
  103757. var timerQuery = caps.timerQuery;
  103758. if (!timerQuery) {
  103759. return null;
  103760. }
  103761. var token = new BABYLON._TimeToken();
  103762. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103763. if (caps.canUseTimestampForTimerQuery) {
  103764. token._startTimeQuery = this._createTimeQuery();
  103765. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  103766. }
  103767. else {
  103768. if (this._currentNonTimestampToken) {
  103769. return this._currentNonTimestampToken;
  103770. }
  103771. token._timeElapsedQuery = this._createTimeQuery();
  103772. if (timerQuery.beginQueryEXT) {
  103773. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103774. }
  103775. else {
  103776. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103777. }
  103778. this._currentNonTimestampToken = token;
  103779. }
  103780. return token;
  103781. };
  103782. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  103783. var caps = this.getCaps();
  103784. var timerQuery = caps.timerQuery;
  103785. if (!timerQuery || !token) {
  103786. return -1;
  103787. }
  103788. if (caps.canUseTimestampForTimerQuery) {
  103789. if (!token._startTimeQuery) {
  103790. return -1;
  103791. }
  103792. if (!token._endTimeQuery) {
  103793. token._endTimeQuery = this._createTimeQuery();
  103794. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  103795. }
  103796. }
  103797. else if (!token._timeElapsedQueryEnded) {
  103798. if (!token._timeElapsedQuery) {
  103799. return -1;
  103800. }
  103801. if (timerQuery.endQueryEXT) {
  103802. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  103803. }
  103804. else {
  103805. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  103806. }
  103807. token._timeElapsedQueryEnded = true;
  103808. }
  103809. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103810. var available = false;
  103811. if (token._endTimeQuery) {
  103812. available = this._getTimeQueryAvailability(token._endTimeQuery);
  103813. }
  103814. else if (token._timeElapsedQuery) {
  103815. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  103816. }
  103817. if (available && !disjoint) {
  103818. var result = 0;
  103819. if (caps.canUseTimestampForTimerQuery) {
  103820. if (!token._startTimeQuery || !token._endTimeQuery) {
  103821. return -1;
  103822. }
  103823. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  103824. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  103825. result = timeEnd - timeStart;
  103826. this._deleteTimeQuery(token._startTimeQuery);
  103827. this._deleteTimeQuery(token._endTimeQuery);
  103828. token._startTimeQuery = null;
  103829. token._endTimeQuery = null;
  103830. }
  103831. else {
  103832. if (!token._timeElapsedQuery) {
  103833. return -1;
  103834. }
  103835. result = this._getTimeQueryResult(token._timeElapsedQuery);
  103836. this._deleteTimeQuery(token._timeElapsedQuery);
  103837. token._timeElapsedQuery = null;
  103838. token._timeElapsedQueryEnded = false;
  103839. this._currentNonTimestampToken = null;
  103840. }
  103841. return result;
  103842. }
  103843. return -1;
  103844. };
  103845. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  103846. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  103847. };
  103848. // We also need to update AbstractMesh as there is a portion of the code there
  103849. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  103850. var engine = this.getEngine();
  103851. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  103852. this._isOccluded = false;
  103853. return;
  103854. }
  103855. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  103856. this._isOccluded = false;
  103857. return;
  103858. }
  103859. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  103860. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  103861. if (isOcclusionQueryAvailable) {
  103862. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  103863. this._isOcclusionQueryInProgress = false;
  103864. this._occlusionInternalRetryCounter = 0;
  103865. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  103866. }
  103867. else {
  103868. this._occlusionInternalRetryCounter++;
  103869. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  103870. this._isOcclusionQueryInProgress = false;
  103871. this._occlusionInternalRetryCounter = 0;
  103872. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  103873. // if strict continue the last state of the object.
  103874. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  103875. }
  103876. else {
  103877. return;
  103878. }
  103879. }
  103880. }
  103881. var scene = this.getScene();
  103882. if (scene.getBoundingBoxRenderer) {
  103883. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  103884. if (!this._occlusionQuery) {
  103885. this._occlusionQuery = engine.createQuery();
  103886. }
  103887. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  103888. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  103889. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  103890. this._isOcclusionQueryInProgress = true;
  103891. }
  103892. };
  103893. })(BABYLON || (BABYLON = {}));
  103894. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  103895. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","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 SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","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"};
  103896. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  103897. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103898. globalObject["BABYLON"] = BABYLON;
  103899. //backwards compatibility
  103900. if(typeof earcut !== 'undefined') {
  103901. globalObject["Earcut"] = {
  103902. earcut: earcut
  103903. };
  103904. }
  103905. return BABYLON;
  103906. });